Consider the following code from Java Puzzlers
class Gloam<T>{ String glom(Collection<?> objs ) { System.out.println("collection"); String result = ""; for (Object o : objs ){ result += o; } return result; } int glom(List <Integer> ints ) { System.out.println("List"); int result = 0; for ( int i : ints ) result += i ; return result; } public static void main(String[] args) { List<String> strings = Arrays.asList("1", "2", "3"); System.out.println(new Gloam().glom(strings)); } }
When I run this program, it gives an exception to the cast class, but if I provide a general argument for the Gloam class in the main method, it 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 a class type parameter?
source share