Invoking toString via method reference in Java 8

故事扮演 提交于 2019-11-28 03:19:56

问题


What am I missing? Why do I have to use Object::toString below and not Integer::toString? Does it have anything to do with type erasure with generics?

Arrays.asList(1,2,3).stream().map(Integer::toString).forEach(System.out::println); //Won't compile

Arrays.asList(1,2,3).stream().map(Object::toString).forEach(System.out::println); //Compiles and runs fine

回答1:


This has nothing to do with type erasure.

Look at the error message :

(argument mismatch; invalid method reference
  reference to toString is ambiguous
    both method toString(int) in Integer and method toString() in Integer match)

The Integer class has two toString methods that match the functional interface expected by the map() method. One is static with an int argument, and the other is the toString() method that overrides Object's toString().

The compiler doesn't know if you want to execute this :

Arrays.asList(1,2,3).stream().map(i->Integer.toString(i)).forEach(System.out::println);

or this :

Arrays.asList(1,2,3).stream().map(i->i.toString()).forEach(System.out::println);


来源:https://stackoverflow.com/questions/27885121/invoking-tostring-via-method-reference-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!