Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

java - 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...