Skip to main content
ICT
Lesson A15 - ArrayList
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

C. Object Casts page 5 of 11

  1. 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.

  1. 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).

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

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

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.