Remember the Collections Framework?

All of the Collections Framework classes and interfaces allow you to use generics (but they also allow you to choose not to use generics). 

As I think you’ll see, using generics is almost always the preferred approach.

Vector/Enumeration Example

Here’s the Vector/Enumeration example from before, translated to using generics:

package examples;

import java.util.Enumeration;
import java.util.Vector;

public class VectorExample
{
  public static void main(String[] args)
  {
    Vector<String> vector = new Vector<String>();
    vector.add("Mary");
    vector.add("Frank");
    vector.add("Joe");
    vector.add("Sylvia");
    vector.add("Vanessa");
    
    for (int i = 0; i < vector.size(); i++)
    {
      String name = vector.elementAt(i); // Note NO required cast
      System.out.println(i + ": " + name);
    }
    
    for (Enumeration<String> en = vector.elements(); en.hasMoreElements(); )
    {
      String name = en.nextElement(); // Note NO required cast
      System.out.println(name);
    }
  }
}

which outputs the following (the same as the original):

0: Mary
1: Frank
2: Joe
3: Sylvia
4: Vanessa
Mary
Frank
Joe
Sylvia
Vanessa

ArrayList/Iterator Example

Here is the ArrayList/Iterator example, translated to using generics:

package examples;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample
{
  public static void main(String[] args)
  {
    ArrayList<String> list = new ArrayList<String>();
    list.add("Mary");
    list.add("Frank");
    list.add("Joe");
    list.add("Sylvia");
    list.add("Vanessa");

    for (int i = 0; i < list.size(); i++)
    {
      String name = list.get(i); // Note NO required cast
      System.out.println(i + ": " + name);
    }

    for (Iterator<String> iter = list.iterator(); iter.hasNext(); )
    {
      String name = iter.next(); // Note NO required cast
      System.out.println(name);
    }
  }
}

which produces the output (same as original):

0: Mary
1: Frank
2: Joe
3: Sylvia
4: Vanessa
Mary
Frank
Joe
Sylvia
Vanessa

LinkedList Example

Here is the LinkedList example, translated to using generics:

package examples;

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class LinkedListExample
{
  public static void main(String[] args)
  {
    List<String> list = new LinkedList<String>();
    list.add("Mary");
    list.add("Frank");
    list.add("Joe");
    list.add("Sylvia");
    list.add("Vanessa");

    for (int i = 0; i < list.size(); i++)
    {
      String name = list.get(i); // Note NO required cast
      System.out.println(i + ": " + name);
    }

    for (ListIterator<String> iter = list.listIterator(); iter.hasNext(); )
    {
      String name = iter.next(); // Note NO required cast
      System.out.println(name);
    }
  }
}

This program produces the output (same as the original):

0: Mary
1: Frank
2: Joe
3: Sylvia
4: Vanessa
Mary
Frank
Joe
Sylvia
Vanessa

Stack Example

Here’s the Stack example, translated to using generics:

package examples;

import java.util.Stack;

public class StackExample
{
  public static void main(String[] args)
  {
    Stack<String> stack = new Stack<String>();
    stack.push("Mary");
    stack.push("Frank");
    stack.push("Joe");
    stack.push("Sylvia");
    stack.push("Vanessa");

    while ( !stack.empty() )
    {
      String name = stack.pop(); // Note NO required cast
      System.out.println(name);
    }
  }
}

This program outputs the following (same as the original):

Vanessa
Sylvia
Joe
Frank

Changing the Type

To show how you can change the type, here’s an example of using a stack with Integer elements:

package examples;

import java.util.Stack;

public class IntegerStackExample
{
  public static void main(String[] args)
  {
    Stack<Integer> stack = new Stack<Integer>();
    stack.push(1);
    stack.push(2);
    stack.push(3);
    stack.push(4);
    stack.push(5);

    while ( !stack.empty() )
    {
      Integer value = stack.pop(); // Note NO required cast
      System.out.println(value);
    }
  }
}

which produces the following output:

5
4
3
2

(Notice that I’m using “autoboxing” on both the input and the output.)

Comparable Example

Here’s the ComparableSorter example, translated to using generics:

package examples;

import java.util.Collections;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ComparableSorter
{
  public static void main(String[] args)
  {
    List<String> list = new ArrayList<String>();
    list.add("abc");
    list.add("DEF");
    list.add("ghi");

    // Do the sort
    Collections.sort(list);

    // See results
    Iterator<String> iter = list.iterator();
    while (iter.hasNext())
    {
      String item = iter.next(); // NO cast required
      System.out.println(item);
    }
  }
}

which outputs (same as original):

DEF
abc
ghi

Comparator Example

Here’s the ComparatorSorter example, converted to using generics.

package examples;

import java.util.Collections;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ComparatorSorter
{
  public static void main(String[] args)
  {
    List<String> list = new ArrayList<String>();
    list.add("abc");
    list.add("DEF");
    list.add("ghi");

    // Do the sort
    Collections.sort(list, new CaseInsensitiveComparator() );

    // See results
    Iterator<String> iter = list.iterator();
    while (iter.hasNext())
    {
      String item = iter.next();
      System.out.println(item);
    }
  }
}

class CaseInsensitiveComparator implements Comparator<String>
{
  public int compare(String s1, String s2)
  {
    return s1.toLowerCase().compareTo( s2.toLowerCase() );
  }
}

which outputs (same as the original):

abc
DEF
ghi

HashSet Example

Here is the HashSet example, translated to use generics:

package examples;

import java.util.HashSet;
import java.util.Iterator;

public class HashSetExample
{
  public static void main(String[] args)
  {
    HashSet<String> set = new HashSet<String>();
    set.add("Mary");
    set.add("Frank");
    set.add("Joe");
    set.add("Sylvia");
    set.add("Vanessa");
    set.add("Frank");   // Duplicate

    for (Iterator<String> iter = set.iterator(); iter.hasNext(); )
    {
      String name = iter.next(); // Note NO required cast
      System.out.println(name);
    }
  }
}

It outputs the following (same as the original):

Vanessa
Joe
Frank
Mary
Sylvia

TreeSet Example

Here’s the TreeSet example, translated to using generics:

package examples;

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample
{
  public static void main(String[] args)
  {
    TreeSet<String> set = new TreeSet<String>();
    set.add("Mary");
    set.add("Frank");
    set.add("Joe");
    set.add("Sylvia");
    set.add("Vanessa");
    set.add("Frank");   // Duplicate

    for (Iterator<String> iter = set.iterator(); iter.hasNext(); )
    {
      String name = iter.next(); // Note NO required cast
      System.out.println(name);
    }
  }
}

Here’s the output of the example (same as the original):

Frank
Joe
Mary
Sylvia
Vanessa

TreeSet with Comparator

Here is the TreeSet example with a Comparator, converted to using generics:

package examples;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class ReversedTreeSetExample
{
  public static void main(String[] args)
  {
    TreeSet<String> set = new TreeSet<String>( new ReverseOrderComparator() );
    set.add("Mary");
    set.add("Frank");
    set.add("Joe");
    set.add("Sylvia");
    set.add("Vanessa");
    set.add("Frank");   // Duplicate

    for (Iterator<String> iter = set.iterator(); iter.hasNext(); )
    {
      String name = iter.next(); // Note NO required cast
      System.out.println(name);
    }
  }
}

class ReverseOrderComparator implements Comparator<String>
{
  public int compare(String s1, String s2)
  {
    return -(s1.compareTo(s2));
    // Reverse order by reversing comparison
  }
}

which outputs (same as original):

Vanessa
Sylvia
Mary
Joe
Frank

HashMap Example

Here’s the HashMap class, converted to using generics:

package examples;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMapExample
{
  public static void main(String[] args)
  {
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("Mary", "555-1234");
    map.put("Frank", "555-5678");
    map.put("Joe", "555-9012");
    map.put("Sylvia", "555-3456");
    map.put("Vanessa", "555-7890");
    map.put("Frank", "555-0987");   // Duplicate

    for (Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator(); iter.hasNext(); )
    {
      Map.Entry<String, String> entry = iter.next(); // Note NO required cast
      String key = entry.getKey(); // Note NO required cast
      String value = entry.getValue(); // Note NO required cast
      System.out.println(key + ":" + value);
    }
  }
}

which outputs:

Vanessa:555-7890
Frank:555-0987
Sylvia:555-3456
Mary:555-1234
Joe:555-90

(This is not the same as the original — it’s in a different order — but since it’s a HashMap, the order isn’t guaranteed, anyway.)

TreeMap Example

Here’s the TreeMap example, converted to using generics:

package examples;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class TreeMapExample
{
  public static void main(String[] args)
  {
    TreeMap<String, String> map = new TreeMap<String, String>();
    map.put("Mary", "555-1234");
    map.put("Frank", "555-5678");
    map.put("Joe", "555-9012");
    map.put("Sylvia", "555-3456");
    map.put("Vanessa", "555-7890");
    map.put("Frank", "555-0987");   // Duplicate

    for (Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator(); iter.hasNext(); )
    {
      Map.Entry<String, String> entry = iter.next(); // Note NO required cast
      String key = entry.getKey(); // Note NO required cast
      String value = entry.getValue(); // Note NO required cast
      System.out.println(key + ":" + value);
    }
  }
}

It outputs (same as the original):

Frank:555-0987
Joe:555-9012
Mary:555-1234
Sylvia:555-3456
Vanessa:555-7890

TreeMap with Comparator

Here’s the ReversedTreeMap example, converted to using generics:

package examples;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class ReversedTreeMapExample
{
  public static void main(String[] args)
  {
    TreeMap&lt;String, String> map = 
          new TreeMap&lt;String, String>( new ReverseOrderKeyComparator() );
    map.put("Mary", "555-1234");
    map.put("Frank", "555-5678");
    map.put("Joe", "555-9012");
    map.put("Sylvia", "555-3456");
    map.put("Vanessa", "555-7890");
    map.put("Frank", "555-0987");   // Duplicate

    for (Iterator&lt;Map.Entry&lt;String, String>> iter = map.entrySet().iterator(); iter.hasNext(); )
    {
      Map.Entry&lt;String, String> entry = iter.next(); // Note NO required cast
      String key = entry.getKey(); // Note NO required cast
      String value = entry.getValue(); // Note NO required cast
      System.out.println(key + ":" + value);
    }
  }
}

class ReverseOrderKeyComparator implements Comparator&lt;String>
{
  public int compare(String s1, String s2)
  {
    return -(s1.compareTo(s2));
    // Reverse order by reversing comparison
  }
}

which outputs the following (same as original):

Vanessa:555-7890
Sylvia:555-3456
Mary:555-1234
Joe:555-9012
Frank:555-0987