
En Java 5, apareció una característica nueva: el
autoboxing. Esta característica permite tratar los tipos primitivos de Java como objetos de la clase correspondiente. Es decir, que una variable de tipo
int puede tratarse como un objeto de tipo
Integer. La ventaja del
autoboxing es que es automático: el programador no tiene que hacer nada especial para usarlo, pues el compilador lo hace por él.
Sin embargo, el programador debe seguir teniendo cuidado al programar, pues pueden surgir errores sutiles, y difíciles de encontrar. Para muestra un ejemplo:
Yo tenía un
ArrayList en una clase, y un método que recibe como parámetro un evento. El método debía borrar el elemento i-ésimo de la lista. La implementación parecía sencilla, pues la clase
ArrayList define un método
remove(int i). Esto, junto con el ingenuo uso de
autoboxing, resultó en la siguiente implementación:
public MiClase {
ArrayList lista = // ...
// ...
public void borra(PropertyChangeEvent evt) {
Integer i = evt.getNewValue();
lista.remove(i);
}Pero el código anterior tiene un error, que sólo se manifiesta en tiempo de ejecución. El método que en realidad se ejecuta es
ArrayList.
remove(Object o), lo cual evidentemente es erróneo, pues el
ArrayList buscará el objeto
Integer y no lo encontrará.
Por supuesto, este error también pone de manifiesto un desconocimiento de mi parte del API de Java :-)
--
Starting with Java 5, there is a new feature:
autoboxing. It allows to convert between primitive types and classes automatically. So, a
int variable can be used as an
Integer object. Autoboxing is automatic and the programmer does not must do anything special to use it: the compiler does the magic.
However, the programmer still must be careful, because it could lead to sutil bugs -the hard to find kind one. This is an example:
I had an
ArrayList in a class. I had also a method with an event parameter, and the method should erase the i-nth element of the list. The implementation seemed easy, as
ArrayList implements the
remove(int i) method. This, with the naive use of autoboxing, lead in the following implementation:
public MyClass {
ArrayList list = // ...
// ...
public void erase(PropertyChangeEvent evt) {
Integer i = evt.getNewValue();
lista.remove(i);
}But the code above has a bug -which will reveal itself only at execution time. Actually, the method which is called is
ArrayList .
remove(Object o). The
ArrayList will search for the
Integer object, and it will not find it.
Of course, this bug also shows my ignorance about the Java API :-)