Skip to main content
Lesson 20 - ArrayList
ZIPPDF (letter)
Lesson MenuPreviousNext
  
Object Casts page 5 of 9

  1. One of the difficulties with building array lists with Object for the item type is that methods for returning the items of the array list return things of type Object, instead of the actual item type.

  2. For example, consider the following:

    ArrayList aList = new ArrayList();
    aList.add("Chris");
    String nameString = aList.get(0); // THIS IS A SYNTAX ERROR!
    System.out.println("Name is " + nameString);

    This code creates an ArrayList called aList and adds to the list the single String object "Chris". 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); // THIS IS A 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).

  3. The erroneous instruction can be modified to work as expected by incorporating the (String) cast shown below.

    String nameString = (String)aList.get(0);

Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.