How is the generic type getting inferred here?

后端 未结 3 462
一整个雨季
一整个雨季 2021-01-18 00:23
public static void main(String[] args) {
    Map>> map = getHashMap();
}

static  Map getHashM         


        
3条回答
  •  忘掉有多难
    2021-01-18 00:52

    class XX
      static  T foo(){ return null; }
    
    String  s = XX.foo();
    Integer i = XX.foo();
    

    Java infers that T is String in the 1st case, Integer in the 2nd case.

    What does "infer" mean? It means that Java guesses that in the two statements, the programmer most like wants T==String in the 1st case, T==Integer for the 2nd case, being a nice guy, Java takes these guesses as fact, and programmers do not have to manually specify the Ts

        String  s = XX. foo();
        Integer i = XX.foo();
    

    But really, Java dictates that the return type T must be determined like that.

    I find this thing very fishy, not sure what's the reason behind the design. Probably, when (if) Java adds reifiable types(i.e. the real class of T is available at runtime), the design makes more sense:

    class XX
      static  T foo(){ return new T(); }
    
    String  s = XX.foo();
    Integer i = XX.foo();
    

    I still don't like the fact that the type of a method is context dependent.

提交回复
热议问题