04. Generic Methods

Methods that have generic types in their parameters are known as generic methods. Before we look into these methods, let's look at another example of a generic class.

The Couple Object

This first class uses generics to make a Couple object. The Couple object stores two objects, both containing the same type.

/**
 *  Here is a simple example of a generic class that takes two elements 
 *  of same type.
 * 
 *  @author Code Snipcademy
 *  @version 1.0.0 Dec 31, 2014
 */
 
// If we wanted two separate types, we can have <T, U> instead of just <E>
public class Couple<E> {
  private E first;
  private E second;
 
  public Couple() { first = null; second = null; }
    
  public Couple(E first, E second) {
    this.first = first;
    this.second = second;
  }
 
  public E getFirst() { return first; }
  public E getSecond() { return second; }
 
  public void setFirst(E newFirst) { this.first = newFirst; }
  public void setSecond(E newSecond) {this.second = newSecond; }
 
  // Tester
  public static void main(String[] args) {
    Couple<String> coupleOfStrings = new Couple<>("bobby", "sandy");
    System.out.println(coupleOfStrings.getFirst() + " " 
                    + coupleOfStrings.getSecond());
  }     
} 

Notice that we have to declare that we are using generics with a <E> up at the class definition. Then we place an E where we would be placing that object's type.

When instantiating our class, however, the user must pass in the type of object they choose to store.

Generic Methods

Now let's try to implement a method that takes in parameters of type Couple.

/**
 * This class shows you how to implement a method that uses generics.
 * 
 * The class contains methods to compare two objects and returns whether they are 
 * equal or not.
 *   
 *  @author Code Snipcademy;
 *  @version 1.0.0 Dec 31, 2014
 */  
public class GenericCompare {
 
  // Formal type parameters go before the return type
  public static <K> boolean compareCouple(Couple<K> first, Couple<K> second) {
    return first.getFirst().equals(second.getFirst()) 
                      && second.getSecond().equals(first.getSecond());
  }
 
  // Test class
  public static void main(String[] args) {
    Couple<String> stringPair1 = new Couple<>("hello", "world");
    Couple<String> stringPair2 = new Couple<>("Hello", "WORLD!");
    Couple<String> stringPair3 = new Couple<>("hello", "world");
              
    /** 
     *  The following two statements are equivalent. 
     *  Java knows what type you're trying to use.
     *  This is known as type inference.    
     */ 
    boolean test1 = GenericCompare.<String>compareCouple(stringPair1, stringPair2);
    boolean test2 = GenericCompare.compareCouple(stringPair1, stringPair3);
 
    System.out.println(test1 + " " + test2);
 
  }
}

Here, we have to write a <K> generic subtype to let the compiler know that we will be using generics in our parameters. If we don't include this, the compiler will throw an exception thinking that K is an actual type parameter.

We want to place the <K> right before our return type. This marks our method to be generic.

Take your Linux skills to the next level!

System Admin Handbook

Take your Linux skills to the next level! Try Linux & UNIX

This book approaches system administration in a practical way and is an invaluable reference for both new administrators and experienced professionals. It details best practices for every facet of system administration, including storage management, network design and administration, email, web hosting, scripting, and much more.

$ Check price
74.9974.99Amazon 4.5 logo(142+ reviews)

More Linux & UNIX resources

Learn Enterprise Java Development for a Bright Career

Java, A Beginner's Guide

Learn Enterprise Java Development for a Bright Career Try Java

A book that is simple, direct, terse with easy examples. Simple example programs to guide you as you go, with test exercises at the end for you to judge for yourself how well you understand the program. Learn java faster and efficiently with Java: A Beginner's Guide.

$ Check price
4040Amazon 4.5 logo(245+ reviews)

More Java resources

Ad