本文介绍了Java泛型,Unbound通配符&lt;?&gt; vs&lt; Object&gt;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我已阅读了几个主题,其中涵盖了有关泛型的某些问题,例如他们的与原始类型的关系。但是,我希望在 Java SE中找到的某一行上另行说明根据一句话: 解决方案这里有两个单独的问题。按照你的说法, List< Object> 实际上可以采用任何对象。 List< Number> 至少可以带 Number 对象,当然也可以是任何子类,像整数。 然而,像这样的方法: public void print(List< Number> list); 实际上仅 取一个列表 code>,它完全是 > List< Number> 。它不会接受任何声明为 List< Integer> 的列表。 所以区别在于 List<> 将使用带有任何声明的任何List,但 List< Object> 仅 标记为 List< Object> ,没有别的。 引用简单地指出, List<?> 是一个列表,您完全不知道它的项目是什么类型。因此,除了 null 以外,您不能添加任何内容。 I've read a few topics which cover certain questions about generics, such as their relationship with raw types. But I'd like an additional explanation on a certain line found in the Java SE tutorial on unbound generics .According to a sentence : If I understand well this sentence; the difference between List<?> and List<Object>, is that we can use the type argument List<String> or List<Integer> by implementing the former. While if we implement the later, we can only use the type argument List<Object>. As if List<?> is an upper bound to Object namely List<? Object>.But then the following sentence confuses me, in the sense that according to what I previously understood, List<Object> should only contain instances of the class Object and not something else. 解决方案 There are two separate issues here. A List<Object> can in fact take any object as you say. A List<Number> can take at least Number objects, or of course any subclasses, like Integer.However a method like this:public void print(List<Number> list);will actually only take a List which is exactly List<Number>. It will not take any list which is declared List<Integer>.So the difference is List<?> will take any List with whatever declaration, but List<Object> will only take something that was declared as List<Object>, nothing else.The last quote simply states, that List<?> is a list for which you literally don't know what type its items are. Because of that, you can not add anything to it other than null. 这篇关于Java泛型,Unbound通配符&lt;?&gt; vs&lt; Object&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-14 12:39