What is the difference between Collection & lt ;? & gt; and Collection & lt; Object>?

advertisements

This question already has an answer here:

  • What is the difference between ? and Object in Java generics? 5 answers

1.what is for Collection < ? >

i tested this code:

    Collection<?> l = new ArrayList<String>();
    l.add("s");

i can't add "s" String.So what is for < ? > ? in which situations i will use it?

2.what is the difference between Collection< ? > and Collection< Object >


1.what is for Collection < ? >

Collection<?> designates a Collection whose element type is unknown. Because the element type is unknown, you can never know that any particular object is of a type that the collection accepts, therefore it is not type-safe to add anything to it.

On the other hand, you can always assume that any element you obtain from such a collection is an Object, and you can invoke any of the inquiry and element removal methods.

This is useful and appropriate for collection operations that do not depend on the type of the collection elements.

2.what is the difference between Collection< ? > and Collection< Object >

A Collection<Object> is a collection that may have any Object as an element. The two are similar in that you cannot make any assumption about the types of the elements of such a collection, but they are quite different in that it is safe to add any object to a Collection<Object>. It is the reason why you cannot make assumptions about element types that makes all the difference: for Collection<?> it is that you don't know the type constraint, but for Collection<Object> it is that (you know that) there is no constraint.