[英]Is this raw type assignment type-safe? List<T> = new ArrayList();
I have some code like this: 我有一些像这样的代码:
@SuppressWarnings({"unchecked", "rawtypes"})
List<String> theList = new ArrayList();
Is this type-safe? 这种类型安全吗? I think it is safe because I don't assign the raw type to anything else.
我认为这是安全的,因为我没有将原始类型分配给其他任何东西。 I can even demonstrate that it performs type checking when I call
add
: 我甚至可以证明它在调用
add
时执行类型检查:
theList.add(601); // compilation error
I have read "What is a raw type and why shouldn't we use it?" 我读过“什么是原始类型,我们为什么不使用它?” but I don't think it applies here because I only create the list with a raw type.
但我不认为这适用于此,因为我只创建一个原始类型的列表。 After that, I assign it to a parameterized type, so what could go wrong?
之后,我将其分配给参数化类型,那么可能出现什么问题?
Also, what about this? 还有,这个怎么样?
@SuppressWarnings({"unchecked", "rawtypes"})
List<String> anotherList = new ArrayList(theList);
The first is type-safe because the list is empty, but still not advised. 第一个是类型安全的,因为列表是空的,但仍然没有建议。 There's no benefit in using a raw type here.
在这里使用原始类型没有任何好处 。 Better to design away from a warning than suppress it.
最好设计远离警告而不是压制它。
The second is definitely not type-safe, as theList
may be a List<Integer>
for example: 第二个绝对不是类型安全的,因为
theList
可能是List<Integer>
,例如:
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
List<Integer> integers = new ArrayList<>();
integers.add(0);
List<String> strings = new ArrayList(integers);
// Bang!
String x = strings.get(0);
}
}
Note how the constructor itself is called without an exception - there's no way for it to know what kind of list you're really trying to construct, so it doesn't perform any casts. 注意如何在没有异常的情况下调用构造函数本身 - 它无法知道你真正想要构造什么类型的列表,因此它不会执行任何强制转换。 However, when you then fetch a value, that implicitly casts to
String
and you get a ClassCastException
. 但是,当您获取一个值时,会隐式转换为
String
并获得ClassCastException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.