Is this raw type assignment type-safe? List<T> = new ArrayList();

假如想象 提交于 2019-12-17 10:01:32

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/22203257/is-this-raw-type-assignment-type-safe-listt-new-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!