this question has answer here:
consider following code java puzzlers
class gloam<t>{ string glom(collection<?> objs ) { system.out.println("collection"); string result = ""; (object o : objs ){ result += o; } return result; } int glom(list <integer> ints ) { system.out.println("list"); int result = 0; ( int : ints ) result += ; return result; } public static void main(string[] args) { list<string> strings = arrays.aslist("1", "2", "3"); system.out.println(new gloam().glom(strings)); } } when run program gives class cast exception, if provide generic argument gloam class in main method works fine.
public static void main(string[] args) { list<string> strings = arrays.aslist("1", "2", "3"); system.out.println(new gloam<date>().glom(strings)); } i don't understand how generic works in class type parameter ?
with no generic type passed constructor, types erased , compiler presented choices
string glom ( collection ); int glom ( list ); the type erased strings variable defined in main, type list.
because list more specific collection chooses int glom ( list ).
now, if have specified generic parameter, no type erasure happens, , compiler knows cannot match int glom ( list<integer> ) list<string>, falls string glom ( collection<?> )
Comments
Post a Comment