通配符与原始类型的变量

通配符与原始类型的变量

本文介绍了通用类型:通配符与原始类型的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下方法:

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

这篇关于通用类型:通配符与原始类型的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:41