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 Object
s?
While the compiler does not infer the generic type one might intend, it will enforce type constraints that are explicitly specified. The following invocation results in a type error.
this.<String>plain("", new ArrayList<Integer>()); /* Compiler error. */
The parameterized method <String>plain(String, String) of type Test is not applicable for the arguments (String, ArrayList<Integer>)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments