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

Answer:

You can encapsulate your integers in Integer objects and store them in an ArrayList.


Example Program

ArrayList after three add operations
import java.util.* ;

public class ArrayListEg
{

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

    // Add three String references
    names.add("Amy");
    names.add("Bob");
    names.add("Cindy");
       
    // Access and print out the three String 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 example program creates an ArrayList that holds String references and then adds references to three Strings. The statement

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

creates an ArrayList of String references. The phrase <String> can be read as "of String references". There are "angle brackets" on each side of <String>.

The phrase ArrayList<String> describes both the type of the object (an ArrayList) and the type of data it holds (references to String).

ArrayList is a generic type. Its constructor specifies both the type of object to construct and the type of data it holds. The type of data is placed inside angle brackets like this: <DataType>. Now, when the ArrayList object is constructed, it will hold data of type "reference to DataType".

A program must import the java.util package to use ArrayList.

By default, an ArrayList starts out with 10 empty cells.


QUESTION 5:

Examine the following:

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

What type of data will values hold?


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