Collections in Java 5.0: Generics

Contact Us or call 1-877-932-8228
Collections in Java 5.0: Generics

Collections in Java 5.0: Generics

Java 5.0 added the concept of Generics, which allow data types to be parameterized for a class

In earlier versions of Java, the collection methods to store objects all received a parameter whose type was Object. Therefore, the methods to retrieve elements were typed to return Object. To use a retrieved element, you had to typecast the returned object back to whatever it actually was (and somehow you had to know what it actually was).

The collections in Java 5.0 use a special, new syntax where the type of object is stated in angle brackets after the collection class name.

Instead of ArrayList, there is now ArrayList<E>, where the E can be replaced by any type. Within the class, method parameters and return values can be parameterized with the same type.

public class ArrayList<E> {
	. . .
	public void add(int index, E element) { ... }
	. . .
	public E get(int index) {  }
	. . .
}

For example, an ArrayList of String objects would be ArrayList<String>.

Code Sample:

Java-Collections/Demos/GenericCollectionsTest.java
import java.util.*;

public class GenericCollectionsTest {
  
  public static void main(String[] args) {

    List<String> ls = new ArrayList<String>();
    
    ls.add("Hello");
    ls.add("how");
    ls.add("are");
    ls.add("you");
    ls.add("today");
    
    // using iterator
    StringBuffer result = new StringBuffer();   
    Iterator<String> is = ls.iterator();
    while (is.hasNext()) 
      result.append(is.next().toUpperCase()).append(' ');
    result.append('?');
    System.out.println(result);
    
    // using for-each loop
    result = new StringBuffer();
    for (String s : ls) result.append(s.toLowerCase()).append(' ');
    result.append('?');
    System.out.println(result);

    // old way
    List l = new ArrayList();
    
    l.add("Hello");
    l.add("how");
    l.add("are");
    l.add("you");
    l.add("today");
    
    // using iterator
    result = new StringBuffer();
    Iterator i = l.iterator();
    while (i.hasNext()) 
      result.append(((String)i.next()).toUpperCase()).append(' ');
    result.append('?');
    System.out.println(result);
    
    // using for-each loop
    result = new StringBuffer();
    for (Object o : l) 
      result.append(((String)o).toLowerCase()).append(' ');
    result.append('?');
    System.out.println(result);

  }
}

As you can see, the objects retrieved from the ArrayList are already typed as being String objects. Note the following:

  • We need to have them as String objects in order to call toUpperCase, whereas our previous examples only printed the objects, so being typed as Object was okay.
  • Without generics, we must typecast each retrieved element in order to call toUpperCase.
  • To use an iterator, we would declare the variable to use the same type of element as the collection we draw from, as in Iterator<String>.
Next