问题描述
请考虑以下方法:
public static void listAll(LinkedList list) {
for(Object obj : list)
System.out.println(obj);
}
和
public static void listAll(LinkedList<?> list) {
for(Object obj : list)
System.out.println(obj);
}
这两种方法有什么区别?如果没有区别,为什么我们要使用第二个?
What is the difference between these two methods? If there is no difference, why we should use the second one?
推荐答案
<?>
不允许您在列表中添加对象.请参阅下面的程序.这是我们传递给方法<?>
的列表的特定类型.
特定方式,列表是使用特定类型创建的,并传递给<?>
方法 listAll
.不要与单词 特定的
混淆.
Specific可以是任何普通对象,例如Dog,Tiger,String,Object,HashMap,File,Integer,Long ....,并且列表是无穷的.
JLS
Forces <?>
方法,用于不执行被称为<?>的任何
方法,一旦您定义了(在调用方法中定义,而不是在不相关对象
的添加; named-listAll
中的)中包含了特定类型
的对象的列表.
这就像<?>
所说的请勿触摸我".
<?>
doesn't allow you to add objects in list. See the program below. It is specific type of list we have passed to method <?>
.
Specific means, list was created with specific type and passed to <?>
method listAll
. Don't confuse with word specific
.
Specific can be any normal object, like, Dog, Tiger, String, Object, HashMap, File, Integer, Long.... and the list is endless.JLS
forces <?>
method for not to perform add any irrelevant objects
in called <?>
method once you have defined (defined in calling method not in called-listAll
) list containing specific type
of object.
It is like <?>
saying "don't touch me".
public static void listAll(LinkedList list)
{
list.add(new String()); //works fine
for(Object obj : list)
System.out.println(obj);
}
public static void listAll(LinkedList<?> list)
{
list.add(new String()); //compile time error. Only 'null' is allowed.
for(Object obj : list)
System.out.println(obj);
}
现在让我们看一下不同的情况.当我们声明特定类型(如Dog,Tiger,Object,String .....)时,会发生什么.让我们将方法更改为特定类型
.
Now let's look at the different scenario. What will happen when we declare specific type like, Dog, Tiger, Object, String ..... anything. Let's change the method to specific type
.
public static void listAll(LinkedList<String> list)// It is now specific type, 'String'
{
list.add(new String());//works fine. Compile time it knows that 'list' has 'String'
for(Object obj : list)
System.out.println(obj);
}
这篇关于通用类型:通配符与原始类型的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!