Concept
Home ] Up ] [ Concept ] The Collections Framework ]

 

 

What's a Generic Class?

It's a class with one or more type variables.  Here's a simple example:

package examples;

/**
 * A simple class to represent a pair of values
 * of potentially different types.
 *
 */
public class Pair<T1, T2>
{ 
  /** 
   * Creates a new instance of Pair 
   */
  public Pair(T1 first, T2 second)
  {
    m_first = first;
    m_second = second;
  }
  
  public T1 getFirst() 
  { 
    return m_first; 
  }
  
  public void setFirst(T1 value)
  {
    m_first = value;
  }
  
  public T2 getSecond() 
  { 
    return m_second; 
  }
  
  public void setSecond(T2 value)
  {
    m_second = value;
  }
  
  private T1 m_first;
  private T2 m_second;
}

and here's a very simple class to test it out:

package examples;

public class PairTest
{
  public static void main(String[] args)
  {
    Pair<String, Integer> pair1 = 
      new Pair<String, Integer>("Fred Bloggs", 5);
    
    System.out.println( pair1.getFirst() + " owns " + pair1.getSecond() );
  }
}

This outputs:

Fred Bloggs owns 5

I could have chosen any combination of types (other than primitive types) for my purposes.

In other words, I am able to write a generally useful class and parameterize it with types.  Then, I can specify the types that I need when I come to use that class.

 

This page was last modified on 27 November, 2007