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

Answer:

No. Only object references can be placed into an ArrayList. (However, you can place references to the objects of the wrapper class Integer that encapuslates integers.)

Example Program

Here is a small example program that uses ArrayList. The program creates an ArrayList that holds String references and then adds references to three Strings. The program must import the java.util package.


import java.util.* ;

class ArrayListEg
{

  public static void main ( String[] args)
  {
    // Create an ArrayList that holds references to String
    ArrayList<String> names = new ArrayList<String>();

    // Add three Object references
    names.add("Amy");
    names.add("Bob");
    names.add("Cindy");
       
    // Access and print out the three Objects
    System.out.println("element 0: " + names.get(0) );
    System.out.println("element 1: " + names.get(1) );
    System.out.println("element 2: " + names.get(2) );
  }
}


The statement

    ArrayList<String> names = new ArrayList<String>();

creates an ArrayList of String references. The phrase <String> can be read as "of String references". The phrase ArrayList<String> describes both the type of the object that is constructed (an ArrayList) and the type of data it will hold (references to String). It starts out with 10 empty cells.

ArrayList is a generic type, which means that its constructor specifies both the type of the object that is constructed and the type that the object will hold. The type the object will hold is placed inside angle brackets <DataType>. When the ArrayList object is constructed, it will be set up to hold data of type "reference to DataType".

QUESTION 5:

Examine the following:

    ArrayList<Integer> values = new ArrayList<Integer>();

What type of data will values hold?