通过Java 8中的方法引用调用toString
问题描述:
我错过了什么?为什么我必须在下面使用 Object :: toString
而不是 Integer :: toString
?它与带有泛型的类型擦除有什么关系吗?
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
答
这无关使用类型擦除。
查看错误消息:
(argument mismatch; invalid method reference
reference to toString is ambiguous
both method toString(int) in Integer and method toString() in Integer match)
Integer
类有两个匹配的 toString
方法 map()
方法所期望的功能接口。一个是带有 int
参数的静态,另一个是覆盖 toString()
方法>对象's toString()
。
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);
或者这个:
Arrays.asList(1,2,3).stream().map(i->i.toString()).forEach(System.out::println);