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.
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,
recall autoboxing:
the 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<>();
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 operator.
Is the following likely to work?
ArrayList<Integer> data = new ArrayList<String>();