How wildcards work in Java
I'm reading a java tutorial on wildcards in generics In the following code:
void printCollection(Collection<Object> c) { for (Object e : c) { System.out.println(e); } }
Does this mean that set C has type objects as its elements, and we can't call C. add ("apple"), because "apple" is a string and the for loop gets any object elements from set C?
But I don't understand the following code,
void printCollection(Collection<?> c) { for (Object e : c) { System.out.println(e); } }
This code uses wildcards to represent "a collection whose element type matches anything" Does this mean that we can add any type of object, such as C. add ("string");, c.add(1); And C. add (New apple())? And the for loop gets any object e from the set C. if C is not an object type, we say that the element of C is integer Is this code valid? Does that mean it should be cast?
Solution
You're almost completely backwards
The collection < Object > can contain its object and subclasses, and since everything (including string) is a subclass of object, you can add anything to this kind of collection However, you cannot make any assumptions about their contents unless they are objects
On the other hand, a collection Contains only instances of a specific unknown type (and its subclasses), but because you don't know what type it is, you can't add anything to such a collection (except null) or make any assumptions about anything in it (except them) 'objects, because everything is)