问题
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