As you use generic types with utility classes, you may often find that number types aren’t very helpful when specified as the object types, as they aren’t equal to their primitive counterparts.
List<Integer> ints = new ArrayList<Integer>();
List<Integer> ints = new ArrayList<>();
Fortunately, expressions that evaluate to int
can be used in place of an Integer
when it is needed.
for (int i = 0; i < 10; i++)
ints.add(i);
The ints.add(i);
statement is equivalent to:
ints.add(Integer.valueOf(i));
And retains properties from Integer#valueOf
such as having the same Integer
objects cached by the JVM when it is within the number caching range.
This also applies to:
byte
and Byte
short
and Short
float
and Float
double
and Double
long
and Long
char
and Character
boolean
and Boolean
Care must be taken, however, in ambiguous situations. Consider the following code:
List<Integer> ints = new ArrayList<Integer>();
ints.add(1);
ints.add(2);
ints.add(3);
ints.remove(1); // ints is now [1, 3]
The java.util.List
interface contains both a remove(int index)
(List
interface method) and a remove(Object o)
(method inherited from java.util.Collection
). In this case no boxing takes place and remove(int index)
is called.
One more example of strange Java code behavior caused by autoboxing Integers with values in range from -128
to 127
: