java - Generic method without parameters -
i confused code includes generic method takes no parameters, return generic type of such method, eg:
static <t> example<t> getobj() { return new example<t>() { public t getobject() { return null; } }; }
and called via:
example<string> exm = getobj(); // accepts string in case or object ,
the interface example's
defination is:
public interface example<t> { t getobject(); }
my question:example<string> exm
accepting string, object , everything. @ time generic return type specified string , how??
the compiler infers type of t
concrete type used on lhs of assignment.
from this link:
if type parameter not appear in types of method arguments, compiler cannot infer type arguments examining types of actual method arguments. if type parameter appears in method's return type, compiler takes @ context in return value used. if method call appears righthand side operand of assignment, compiler tries infer method's type arguments static type of lefthand side operand of assignment.
the example code in link similar 1 in question:
public final class utilities { ... public static <t> hashset<t> create(int size) { return new hashset<t>(size); } } public final class test public static void main(string[] args) { hashset<integer> hi = utilities.create(10); // t inferred lhs `integer` } }
Comments
Post a Comment