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

前端 未结 1 1521
忘了有多久
忘了有多久 2020-12-02 02:00

I have some code like this:

@SuppressWarnings({\"unchecked\", \"rawtypes\"})
List theList = new ArrayList();

Is this type-saf

相关标签:
1条回答
  • 2020-12-02 02:53

    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.

    0 讨论(0)
提交回复
热议问题