I am reading a java tutorial about Wildcards in Generics. In the following code:
void printCollection(Collection<Object> c) { for (Object e : c) { System.out.println(e); } }
Does this mean that the collection c accepts the object type as its elements, and we cannot call c.add("apple") because "apple" is a string, and the for loop accepts any object elements from the collection c ?
But I do not understand the following code,
void printCollection(Collection<?> c) { for (Object e : c) { System.out.println(e); } }
This code uses wildcards, which means "a collection whose element type matches something." Does this mean that we can add any type of object to it, for example c.add("string"); , c.add(1); and c.add(new apple()); ? and the for loop takes any object e from the collection c , if c not of type object , we say that c are Integer elements. Does this code work? Does this mean that it should be thrown?
user707549
source share