Computer Science Canada

Passing values to ArrayList

Author:  Martin [ Wed Sep 22, 2004 6:29 pm ]
Post subject:  Passing values to ArrayList

How can I add values to an ArrayList?

my code looks as follows:
ArrayList test = new ArrayList();
test.add (0);

Clearly this doesn't work. What do I do?

Author:  wtd [ Wed Sep 22, 2004 6:45 pm ]
Post subject: 

ArrayList objects can only contain items of type Object. All classes inherit from Object, so any object can be added, but Java also has primitive types. Primitive types, such as int, long, float, double, boolean, are denoted by starting with a lowercase letter, and are not objects.

In order to add such things to an ArrayList, you have to first "box" the primitive up in an object.

code:
ArrayList arr = new ArrayList();

arr.add(new Integer(0));

int firstElement = ((Integer)arr.get(0)).intValue();


It gets very messy.

Java 5 greatly improves this in two ways. Generics are somewhat similar to templates in C++ or well... generics in Eiffel and Ada95. They grealy improve collections in those languages, and they greatly improve collections in Java (though not nearly as much as in the other languages).

Secondly, Java 5 provides auto-boxing. This feature automatically converts primitive types to and from object types when necessary.

ArrayList can still only accept things of type Object, but with auto-boxing this isn't a problem.

code:
ArrayList<Integer> arr = new ArrayList<Integer>();

arr.add(0);

int firstElement = arr.get(0);


: