通过Java 8中的方法引用调用toString [英] Invoking toString via method reference in Java 8

查看:107
本文介绍了通过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);

这篇关于通过Java 8中的方法引用调用toString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆