CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Collections

Collections and Generics
ArrayList class
Code

Code that uses an array list of type String

//To find out the number of elements in a list, we use its size method.
List<String> sample = new ArrayList<String>();

sample.add("One Java");
sample.add("One Java");
sample.add("One Java");

System.out.println(sample.size());

Resulting output

3

Code that uses an array list of type String

// create an array list of type String
ArrayList<String> codes = new ArrayList<String>();

// add three strings
codes.add("mbdk");
codes.add("citr");
codes.add(0, "warp");

// print the array list
for (int i =0; i < codes.size(); i++)
{
    String code = codes.get(i);
    System.out.println(code);
}

Resulting output

warp
mbdk
citr

Another way to display the contents of a collection

System.out.println(codes);

Resulting output

[warp, mbdk, citr]

Code that replaces and deletes objects

codes.set(1,"wuth");
codes.remove("warp");
codes.remove(1);

System.out.print(codes);

Resulting output

[wuth]

Code that uses an array list of type Integer

ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(1);
numbers.add(2);
numbers.add(3);

System.out.println(numbers);

Resulting output

[1, 2, 3]

When you use generics to create a collection that holds a wrapper type, the compiler automatically converts the primitive type to its wrapper type and vice versa using a technique called autoboxing.

Lists and Primitive data Types

With an array, we can store either primitive data values (int, double, etc.) or objects. With a list, we can store only objects. If we need to store primitive data values in a list, then we must use wrapper clases such as Integer, Float, and Double. To add integers to a list, we have to do something like this:

List<Integer> intList = new Arraylist<Integer>();
intList.add(new Integer(12));
intList.add(new Integer(14));
...

When we access the elemnts of intList, which are Integer objects, we need to use the intValue method to get the integer value. The following code computes the sum of integer values stored in inList:

int sum = 0;
for (Integer intObj: intList) {
	sum = sum + intObj.intValue();
}

Java 5.0 introduces automatic boxing and unboxing features. With Java 5.0, we can write the code as if we could store primitive data values in lists. For example, the following code is valid with Java 5.0:

List intList = new Arraylist();
intList.add(12);
intList.add(14);
...
int sum = 0;
for (int value: intList) {
	sum = sum + value;
}

When we write

intList.add(12);
the compiler translates it to
intList.add(new Integer(12));
This is called auto boxing. And when we write
int num = intList.get(1);
the compiler translates it to
int num = intList.get(1).intValue();

This is called auto unboxing.

Previous | Class | Code | Which is Better? | Next