I have some code like this:
@SuppressWarnings({\"unchecked\", \"rawtypes\"})
List theList = new ArrayList();
Is this type-saf
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
.