go to previous page   go to home page   go to next page

Answer:

ArrayList<String> names = new ArrayList<String>();
names.add( 34 );

No. The ArrayList<String> can only hold references to String. The compiler will complain if you try to put something else in it.


Type Wrappers

The following will work, however:

ArrayList<Integer> data = new ArrayList<Integer>();
data.add( 34 );

It looks as if the primitive int 34 is added to the ArrayList. However, what really happens is compiler automatically constructs an Integer wrapper class containing 34, and a reference to that object is added to the array. The following will also work:

ArrayList<Integer> data = new ArrayList<>(); // diamond
data.add( 34 );

The declaration ArrayList<Integer> data specifies the type of element the list will hold. This information does not need to be repeated in the constructor: new ArrayList<>(). The empty pair of angle brackets <> is called a diamond.


QUESTION 4:

Is the following likely to work?

ArrayList data = new ArrayList();
data.add( "Might work" );

go to previous page   go to home page   go to next page