这种原始类型分配类型安全吗?列表与LT; T> = new ArrayList(); [英] Is this raw type assignment type-safe? List<T> = new ArrayList();
问题描述
@SuppressWarnings({unchecked,rawtypes})
列表< String> theList = new ArrayList();
这种类型安全吗?我认为这是安全的,因为我不把原始类型分配给其他任何东西。当我调用 add
时,我甚至可以证明它执行类型检查:
theList.add(601); //编译错误
我已阅读 什么是原始类型,为什么我们不应该使用它? / a>,但我不认为它适用于此,因为我只用
另外,这又如何?
@SuppressWarnings({unchecked,rawtypes})
List< String> anotherList = new ArrayList(theList);
第一种是类型安全的,因为列表为空,但仍然没有建议。在这里使用原始类型没有好处。第二个肯定是不是类型安全的,因为 theList 可能是
列表<整数>
,例如:
import java.util。*;
public class Test {
public static void main(String [] args)throws Exception {
List< Integer>整数= new ArrayList<>();
integers.add(0);
列表< String> strings = new ArrayList(整数);
// Bang!
String x = strings.get(0);
$ b $ p
$ b 请注意构造函数本身是如何在没有异常的情况下被调用的 - 没有办法让它知道你真的试图构建什么样的列表,所以它不会执行任何转换。但是,如果您然后获取值,则隐式转换为 String
,您将得到 ClassCastException
。
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
:
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:
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
.
这篇关于这种原始类型分配类型安全吗?列表与LT; T> = new ArrayList();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!