更新时间:2023-02-26 22:14:32
第一种是类型安全的,因为列表为空,但仍然没有建议。在这里使用原始类型没有好处。第二个肯定是不是类型安全的,因为 theList $ c>可能是
列表<整数>
,例如:
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
.