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.

Learn Enterprise Java Development for a Bright Career

Effective Java

Learn Enterprise Java Development for a Bright Career Try Java

Are you looking for a deeper understanding of the Java so that you can write code that is clearer, more correct, more robust, and more reusable? Look no further! Effective Java brings together seventy-eight indispensable programmer's rules of thumb: working, best-practice solutions for the programming challenges you encounter every day.

$ Check price
54.9954.99Amazon 4.5 logo(219+ reviews)

More Java resources

Take your Linux skills to the next level!

The Linux Command Line

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

The Linux Command Line takes you from your very first terminal keystrokes to writing full programs in Bash, the most popular Linux shell. Along the way you'll learn the timeless skills handed down by generations of gray-bearded, mouse-shunning gurus: file navigation, environment configuration, command chaining, pattern matching with regular expressions, and more.

$ Check price
39.9539.95Amazon 4.5 logo(274+ reviews)

More Linux & UNIX resources