简体   繁体   中英

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 :

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM