为什么不将Collection简单地视为Collection&lt ;? [英] Why is Collection not simply treated as Collection<?>

查看:88
本文介绍了为什么不将Collection简单地视为Collection&lt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下来自Shiro的

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);

是的,即使是现在,仍然有使用原始类型的库,可能是为了保留Java 1.5之前的兼容性?!

如果我现在想将此方法与流或诸如此类的可选参数一起使用:

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:

类型安全:方法collect(Collector)属于原始类型Stream.引用通用类型Stream< T>.应该参数化

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

javac:

注意:GenericsTest.java使用未经检查或不安全的操作.

Note: GenericsTest.java uses unchecked or unsafe operations.

由于我无法更改API方法的签名来摆脱此警告,因此可以使用@SuppressWarnings("unchecked")进行注释,也可以像这样将其强制转换为Collection<?>:

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());

由于这种转换当然总是有效,所以我想知道为什么编译器不仅仅将Collection视为Collection<?>而是警告这种情况.添加注释或强制转换不会单单改善代码,但会降低可读性,甚至可能掩盖有关使用非参数类型的实际有效警告.

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.

推荐答案

原因很简单:

您可以从Collection<?>中读取Object,方法与从Collection中读取相同. 但是,您不能将Object添加到Collection<?>(编译器禁止这样做),而可以将Object添加到Collection.

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.

如果Java 5发行后编译器将每个Collection都转换为Collection<?>,那么以前编写的代码将不再编译,从而破坏了向后兼容性.

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.

这篇关于为什么不将Collection简单地视为Collection&lt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆