Why is Collection not simply treated as Collection<?>

后端 未结 4 1633
猫巷女王i
猫巷女王i 2021-01-01 09:03

Consider the following API method taken from Shiro\'s org.apache.shiro.subject.PrincipalCollection interface but probably present in other libraries as well:



        
相关标签:
4条回答
  • 2021-01-01 09:12

    The reason is quite simple:

    You may read Objects from a Collection<?> the same way as from Collection. But you can't add Objects to a Collection<?> (The compiler forbids this) whereas to a Collection you can.

    If after the release of Java 5 the compiler had translated every Collection to Collection<?>, then previously written code would not compile anymore and thus would destroy the backward compatibility.

    0 讨论(0)
  • 2021-01-01 09:26

    The major difference between raw type and unbounded wildcard <?> is that the latter is type safe, that is, on a compile level, it checks whether the items in the collection are of the same type. Compiler won't allow you to add string and integer to the collection of wildcard type, but it will allow you to do this:

    List raw = new ArrayList();
    raw.add("");
    raw.add(1);
    

    Actually, in case of unbounded wildcard collections (List<?> wildcard = new ArrayList<String>()), you can't add anything at all to the list but null (from Oracle docs):

    Since we don't know what the element type of c stands for, we cannot add objects to it. The add() method takes arguments of type E, the element type of the collection. When the actual type parameter is ?, it stands for some unknown type. Any parameter we pass to add would have to be a subtype of this unknown type. Since we don't know what type that is, we cannot pass anything in. The sole exception is null, which is a member of every type.

    0 讨论(0)
  • 2021-01-01 09:26

    A Collection<?> screams:

    Please don't add anything to me. I have a strict content type, ... well uh, I just forgot what type it is.

    While a Collection says:

    It's all cool ! You can add whatever you like, I have no restrictions.

    So, why shouldn't the compiler translate Collection to Collection<?> ? Because it would put up a lot of restrictions.

    0 讨论(0)
  • 2021-01-01 09:29

    A use-case that I can think of as to why Collection is not considered as Collection<?> is let say we have a instance of ArrayList

    Now if the instance is of type ArrayList<Integer> or ArrayList<Double> or ArrayList<String>, you can add that type only(type checking). ArrayList<?> is not equivalent to ArrayList<Object>.

    But with only ArrayList, you can add object of any type. This may be one of the reason why compiler is not considering ArrayList as ArrayList<?> (type checking).

    One more reason could be backward compatibility with Java version that didn't have generics.

    0 讨论(0)
提交回复
热议问题