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:
ListintList = new Arraylist (); intList.add(12); intList.add(14); ... int sum = 0; for (int value: intList) { sum = sum + value; }
When we write
the compiler translates it tointList.add(12);
This is called auto boxing. And when we writeintList.add(new Integer(12));
the compiler translates it toint num = intList.get(1);
int num = intList.get(1).intValue();
This is called auto unboxing.