本文介绍了为什么我不能添加到列表<?扩展字符串>在爪哇?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码段中,将Hulooo"添加到列表会产生编译器错误,因为 String 不扩展 String.但是,对字符串的 ArrayList 进行类型转换是有效的.但是对对象的 ArrayList 进行类型转换不起作用.

In the snippet below, adding "Hulooo" to the list generates a compiler error since String doesnt extend String.However, typecasting an ArrayList of strings works. But typecasting an ArrayList of objects doesn't work.

有人可以解释为什么会发生这种情况吗?什么适用于字符串(在此上下文中)而不适用于对象?

Can someone explain why this is happening?What applies to String(in this context) that doesn't apply to Object?

public static void takeList(List<? 

推荐答案

问号 ? 是所谓的通配符..String 是 final 类,因此没有 String 的子类型,但编译器不考虑这个.因此,编译器假定该列表可能是 String 的某个子类型的列表,并且不可能将 String 添加到这样的列表中.

The question mark ? is a so-called wild-card operator. List<? means: any type List<T> where T is String or a sub-type of String. String is a final class, and thus there are no sub-types of String, but the compiler does not look at this. And thus, the compiler assumes that the list could be a list of some sub-type of String, and it would not be possible to add Strings to such a list.

让我们用一个非最终类 A 来模拟你的例子,它有一个子类 B:

Let's simulate your example with a non-final class, A, which has a sub-class, B:

class A {
    // empty
}

class B 

现在考虑与您的方法等效的方法:

And now consider the equivalent to your method:

public static void takeList(List<? 

这不会编译,原因如下.假设您按如下方式调用此方法:

This will not compile, for the following reason. Suppose you call this method as follows:

List<B> myList = new ArrayList<>();   // line 1
takeList(myList);                     // line 2
B element = myList.get(0);            // line 3
B.f();                                // line 4

由于BA的子类,所以第2行的函数调用是合法的.但是方法takeList 将一个A 添加到列表中,它不是B.然后 B 的列表包含一个不是 B 的元素,第 3 行和第 4 行分解.

Since B is a sub-class of A the function call in line 2 is legal. But the method takeList adds an A to the list which is not a B. An then the list of Bs contains an element which is not a B, and line 3 and 4 break down.

类型系统是为了防止输入错误,所以如果有一种情况你可以将错误类型的对象添加到列表中,类型系统必须禁止它.

The type system is there to prevent typing errors, so if there is one scenario where you could add an object of the wrong type to a list, the type system must forbid it.

这篇关于为什么我不能添加到列表<?扩展字符串>在爪哇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:36
查看更多