java generics, unchecked warnings

萝らか妹 提交于 2019-12-04 10:24:34
Péter Török

my question would be why is the static type List<Number> and not just List?

So that the compiler can catch bugs like the above already at compilation time, instead of runtime. This is the main point of generics.

Why in this code instead of elArray = new ListaConPI[numVertices+1] wouldnt we write elArray = new ListaConPI<Adyacente>[numVertices+1]?

Because you can't instantiate arrays of generic types (although you can declare such arrays as variables or method parameters). See this earlier answer of mine to the same question.

List l = // something;

What is the type of l? Its a List, that's its static type, it could be any old List. Hence if you assign

List<String> listOfString = l;

The compiler at compile time cannot know whether this is safe. The example you show demonstrates that it is unsafe, and the ClassCastException results.

Please, read about type erasure. Now, reconsider your code after erasing the types (I'll do only the first example):

List l = new ArrayList(); // Compiler remembers that it should check that only numbers can be added
List ls = l; // Compiler remembers that it should cast everything back to a String
l.add(0, new Integer(42)); // the compiler checks that the second parameter is a Number.
String s = ls.get(0); // The compiler casts the result back to a String, so you get an exception

For the same reason, you cannot have a class like this:

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