Java generic methods in generics classes

后端 未结 6 1740
粉色の甜心
粉色の甜心 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条回答
  •  猫巷女王i
    2020-11-29 02:16

    I've found one reason to fully discard generics (however it's not quite good). Reason is: generics may be bounded. Consider this class:

    public static class MyGenericClass {
        public  K doSomething(K k){
            return k;
        }
    
        public  List makeSingletonList(K k){
            return Collections.singletonList(k);
        }
    }
    

    The compiler has to discard generics in doSomething, when you use the class without generics. And I think all generics are discarded to be consistent with this behavior.

    makeSingletonList compiles because Java does an unchecked cast from List to List (however compiler displays warning).

提交回复
热议问题