我正在阅读作者Jeanne Boyarsky 和 Scott Selikoff 的 OCP 书籍,书上说:第 122 页
? super String
有了下限,我们告诉 Java 该列表将是一个 String 对象列表 或一个 一些String父类(super class)对象的列表
List<? super String> superString = new ArrayList<>();
superString.add(new String());// Valid
superString.add(new Object()); // Not Valid ? Why?. Object is a super class of String
其他示例:
List<? super IOException> exceptions = new ArrayList<Exception>();
exceptions.add(new Exception()); // Invalid, why ? Exception is a superclass of IOException
exceptions.add(new IOException());
exceptions.add(new FileNotFoundException());
我认为这个说法
With a lower bound, we are telling Java that the list will be a list of String objects or a list of some objects that are a superclass of String
应该
With a lower bound, we are telling Java that the list will be a list of String objects or a list of some objects whoes super class is String
如果这种情况属实,那么我们为什么使用
List<? super IOException> exceptions = new ArrayList<Exception>();
而不是
List<? super IOException> exceptions = new ArrayList<IOException>();
最佳答案
您需要了解,这些边界(下限和上限)的存在是为了限制/指定变量的类型,而不是为了限制/指定此类集合内元素的类型。
一个例子:
List<? super String> variable = new ArrayList<CharSequence>();
使用此语句,您首先创建一个 ArrayList
其元素可以是 CharSequence
类型或其子类型(例如 String
或 StringBuilder
)。
通过该声明,应该清楚您不能添加 Object
进入这个列表。它根本没有实现CharSequence
界面。编译器会处理这个问题。
存在用于创建泛型类型的子类型的下限和上限。它们的使用在this question about PECS中有解释。 .
事实上,一个List<? super String>
是一个具有具体元素类型的列表,但目前还不知道该具体类型。请参阅我的初始化示例。具体类型为CharSequence
。它只是意味着所有元素都属于该具体类型(或子类型),但在变量自己的类型中是未知的。
关于java - ? Java super 字符串下界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37961924/