No.
The non-empty cells of an ArrayList
must contain object references (or null
).
To put an int
into an ArrayList
use the Integer
wrapper class and autoboxing.
(See chapter 11 for a discussion of autoboxing.)
Now the object can be put into an ArrayList
.
The following program builds a list of integers and then writes them out.
import java.util.* ; public class WrapperExample { public static void main ( String[] args) { ArrayList<Integer> data = new ArrayList<Integer>(); data.add( 1 ); // add an Integer object containing 1 data.add( 3 ); data.add( 17 ); data.add( 29 ); for ( Integer val : data ) System.out.print( val + " " ); System.out.println( ); } }
It looks as if the int
1 is directly added to the list.
But this is NOT what happens.
The statement data.add( 1 )
first creates an Integer
object
by using autoboxing.
Then the reference to that object is added to the list at index 0.
The program writes out:
1 3 17 29
The picture shows that the ArrayList
contains an array of object
references, as always.
It shows the int
s each contained in a little box that
represents the wrapper object.
Would this statement work in the program?
data.add( new Integer(1) );