This will not be covered on the AP exam, but your students will discover it on their own, accidentally...
When necessary, Java automatically converts int
s into
Integer
s and vice versa. You can write:
Without autoboxing, this would have to be written:ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(3); numbers.add(5); int total = 0; for(int i : numbers) total += i;
ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(new Integer(3)); numbers.add(new Integer(5)); int total = 0; for(Integer i : numbers) total += i.intValue();
Autoboxing is rather problematic. Consider the following example.
Even if the two underlyingif(numbers.get(0) == numbers.get(1)) { // ...
int
s are equal,
the if
's body may not execute, because
this compares Integer
s, not int
s.
(However, it may, because there is some internal caching...)
Another possible unexpected behavior is this:
This uses thestudents.remove(numbers.get(0));
remove
method for removing an
Object
, not the remove
method for
removing the object at an int
index.