Why is Java's type inference so weak?

后端 未结 3 2100
遇见更好的自我
遇见更好的自我 2021-01-05 21:27

Say, I have a method:

public static  Collection addToCollection(T element, Collection collection) {
    collection.add(element);
          


        
相关标签:
3条回答
  • 2021-01-05 21:48

    Collections.emptyList() returns a List<Object> which is passed through your addToCollection() method. And since Object is not Integer, this fails.

    0 讨论(0)
  • 2021-01-05 22:01

    The type inference system has been improved in Java 8, with the introduction of target typing, in order to give more expressivity to streams and lambdas. As a consequence your code compiles with Java 8.

    More about it in the updated tutorial, with a very similar example towards the very bottom of the page.

    0 讨论(0)
  • 2021-01-05 22:05

    Whats harm in doing this?

    Integer i = 42;
    List<Integer> emptyList = Collections.emptyList();
    Collection<Integer> result = addToCollection(i, emptyList);
    

    In java 8 it will be taken care.

    0 讨论(0)
提交回复
热议问题