How patterns work in Java

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?

+7
source share
3 answers

You got it almost exactly back.

A Collection<Object> may contain Object and its subclasses, and since everything (including String ) is a subclass of Object , you can add something to such a collection. However, you cannot make any assumptions about its contents, except that they are Object s.

On the other hand, A Collection<?> Contains only instances of a certain unknown type (and its subclasses), but since you do not know what type it is, you cannot add anything (except null ) to such a collection, and also do not assumptions about its connections (except that they are Object s, because everything is there).

+5
source

In Java Generics Angelika Langer Frequently Asked Questions , the question "What is the difference between an unbounded parametric type of a wildcard type and a raw type?" ( link ) you will see that Collection<?> and Collection<Object> almost equivalent.

0
source

In the case of the second statement "?" A wildcard means that the generic parameter is undefined. As a result, the type is bound to "Object" because this is the default restriction for declarations without declarations.

In fact, even "Integer" is a subclass of Object. If you mean "int", you're right, it is a primitive, not a derivative of Object, but you cannot put it in a collection, since the collection only allows derivatives of an object.

And to the question, if the items placed in the collection should be abandoned. No, this is not necessary, as they are pure derivation classes from Object. The compiler does not need any specific casting information; it automatically allows the correct definition of the class.

0
source

All Articles