A simple Java Generics example class

To take a break from a project I was working on yesterday I gave my brain a little exercise to see if I could remember how to create a Java class that used the Java 5 Generics magic. Since I’ve used Scala a lot recently, I decided to create a Java version of the Scala Tuple class.

The Tuple class simply stores two values, which are often key/value pairs. Beginning with the end in mind, here’s how you would typically use a Tuple in Java (if it existed):

Tuple<String, Integer> t = new Tuple<String, Integer>("age", 41);

As you can see, with Generics you define the variable types on the fly, and in this case I choose to define my key as a String, and my value as an Integer.

My Generics example class

While this gives you a lot of power, defining my example Generics class is actually fairly simple:

class Tuple<K, V> 
{
  private final K k;
  private final V v;
  
  public Tuple(K key, V value) {
    k = key;
    v = value;
  }

  public String toString() {
    return String.format("KEY: '%s', VALUE: '%s'", k, v);
  }
  
}

As you can see, following the Generics specification, I add my field types to the “class” definition line, then use the same strings “K” and “V” in my class where I would normally declare a class type like String, Integer, Float, etc.

A Generics example class

If you want to experiment with this on your own, here’s the complete source code for my Java Generics example class:

public class GenericsTest {

  public static void main(String[] args) {
    Tuple<String, Integer> t = new Tuple<String, Integer>("foo", 1);
    System.out.println(t);
  }

}

class Tuple<K, V> 
{
  private final K k;
  private final V v;
  
  public Tuple(K key, V value) {
    k = key;
    v = value;
  }

  public String toString() {
    return String.format("KEY: '%s', VALUE: '%s'", k, v);
  }
  
}

Resources

And here are two links to two good Java Generics documentation:

I hope this Generics example has been helpful - enjoy!