Java compilers before J2SE 1.5 (codename: Tiger) did not support the typing of an ArrayList
as shown above. This new feature is called generics. It is a safe way to deal with ArrayLists
. You declare what kind of objects you are going to put in the ArrayList
. Java will only allow you to put that type of object in, and it knows the type of object coming out. In previous versions of Java, you had to tell the compiler what kind of object you were putting in and taking out.
For example, consider the following:
ArrayList aList = new ArrayList();
aList.add("Chris");
String nameString = aList.get(0); // SYNTAX ERROR!
System.out.println("Name is " + nameString);
This code creates an ArrayList
called aList
and adds the single String
object "Chris"
to the list. The intent of the third instruction is to assign the item "Chris"
to nameString
. The state of program execution following the add is that aList
stores the single item, "Chris"
. Unfortunately, this code will never execute, because of a syntax error with the statement:
String nameString = aList.get(0); // SYNTAX ERROR!
The problem is a type conformance issue. The get
method returns an Object
, and an Object
does not conform to a String
(even though this particular item happens to be a String
).
The erroneous instruction can be modified to work as expected by incorporating the (String)
cast shown below.
String nameString = (String)aList.get(0);