Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

java - Why is Collection not simply treated as Collection<?>

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

Collection fromRealm(String realmName);

Yes even nowadays there are still libraries that are using raw-types, probably to preserve pre Java 1.5 compatibility?!

If I now want to use this method together with streams or optionals like this:

principals.fromRealm(realmName).stream().collect(Collectors.toSet());

I get a warning about unchecked conversion and using raw types and that I should prefer using parameterized types.

Eclipse:

Type safety: The method collect(Collector) belongs to the raw type Stream. References to generic type Stream<T> should be parameterized

javac:

Note: GenericsTest.java uses unchecked or unsafe operations.

As I can't change the API method's signature to get rid of this warning I can either annotate with @SuppressWarnings("unchecked") or simply cast to Collection<?> like this:

((Collection<?>) principals.fromRealm(realmName)).stream().collect(Collectors.toSet());

As this cast of course always works I'm wondering why the compilers are not simply treating Collection as Collection<?> but warn about this situation. Adding the annotation or the cast doesn't improve the code a single bit, but decreases readability or might even shadow actual valid warnings about usage of unparameterized types.

question from:https://stackoverflow.com/questions/55514277/why-is-collection-not-simply-treated-as-collection

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...