Java generic methods in generics classes

后端 未结 6 1727
粉色の甜心
粉色の甜心 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:23

    The reason for this is backwards compatibility with pre-generics code. The pre-generics code did not use generic arguments, instead using what seems today to be a raw type. The pre-generics code would use Object references instead of references using the generic type, and raw types use type Object for all generic arguments, so the code was indeed backwards compatible.

    As an example, consider this code:

    List list = new ArrayList();
    

    This is pre-generic code, and once generics were introduced, this was interpreted as a raw generic type equivalent to:

    List list = new ArrayList<>();
    

    Because the ? doesn't have an extends or super keyword after it, it is transformed into this:

    List list = new ArrayList<>();
    
    
    

    The version of List that was used before generics used an Object to refer to a list element, and this version also uses an Object to refer to a list element, so backwards compatibility is retained.

    提交回复
    热议问题