Java generic methods in generics classes

后端 未结 6 1744
粉色の甜心
粉色の甜心 2020-11-29 01:49

If you create a generic class in Java (the class has generic type parameters), can you use generic methods (the method takes generic type parameters)?

Consider the f

6条回答
  •  孤街浪徒
    2020-11-29 02:14

    This doesn't answer the fundamental question, but does address the issue of why makeSingletonList(...) compiles whilst doSomething(...) does not:

    In an untyped implementation of MyGenericClass:

    MyGenericClass untyped = new MyGenericClass();
    List list = untyped.makeSingletonList("String");
    

    ...is equivalent to:

    MyGenericClass untyped = new MyGenericClass();
    List list = untyped.makeSingletonList("String");
    List typedList = list;
    

    This will compile (with several warnings), but is then open to runtime errors.

    Indeed, this is also analogous to:

    MyGenericClass untyped = new MyGenericClass();
    List list = untyped.makeSingletonList("String"); // this compiles!!!
    Integer a = list.get(0);
    

    ...which compiles but will throw a runtime ClassCastException when you try and get the String value out and cast it to an Integer.

提交回复
热议问题