Generic Methods and Type Inferencing in Java

Viewed 1695

Given the following not-very-useful code:

package com.something;

import java.util.ArrayList;
import java.util.Collection;

//Not a generic class!
public class Test {

  public <T> void plain(T param1, T param2) {}
  public <T> void fancy(T param1, Collection<T> param2) {}

  public void testMethod() {

    //No error
    fancy("", new ArrayList<String>());

    //Compiler error here!
    fancy("", new ArrayList<Integer>());

    //No error
    plain("", new ArrayList<Integer>());

  }

}

(Please correct my understanding if it's wrong!)

The 2nd call to fancy() is a compiler error because Java can't infer any common type between the two arguments (can't infer Object since the second parameter must be a Collection.)

The call to plain() is not a compiler error because Java infers the common type of Object between the two arguments.

I recently came across code that had a method signature similar to plain().

My question is this:

Is plain()'s signature useful for anything?

Perhaps the person who wrote that code thought that plain()'s signature would enforce that both parameters have the same type at compile time, which is obviously not the case.

Is there any difference from or benefit to writing a method with a signature like plain() rather than just defining both parameters to be Objects?

3 Answers
Related