【问题标题】:Why does this work for bounded method reference?为什么这适用于有界方法参考?
【发布时间】:2021-06-01 11:25:19
【问题描述】:

在下面的 sn-p 中,[1] 似乎产生了预期的结果,而 [2] 抛出了 ClassCastException,如下面的结果所示。

为什么在调用 iterator() 时会抛出 ClassCastException 而不是在使用方法引用时?

 List<String> philosophers = Arrays.asList("Seneca", "Epictetus");
 // [1]
 for (String s : (Iterable<? extends String>) philosophers::iterator) {
     System.out.println(s);
 }

 // [2]
 for (String s: (Iterable<? extends String>) philosophers.iterator()) {
     System.out.println(s);
 }

[1](使用方法引用时的结果)

`Seneca`
`Epictetus`

[2](调用iterator()时的结果)

Exception in thread "main" java.lang.ClassCastException: class java.util.Arrays$ArrayItr cannot be cast to class java.lang.Iterable` 

【问题讨论】:

    标签: foreach java-8


    【解决方案1】:

    它们是两个不同的东西。

    philosophers::iterator 是一个 函数,当被调用时,它接受 0 个参数并返回一个迭代器。碰巧,这与 Iterable 的定义兼容,因为该接口只有一个抽象方法可以做到这一点。

    philosophers.iterator() 不返回函数;它返回一个迭代器。 Iterator 不是 Iterable,因此强制转换失败。


    如果没有充分的理由去做这两者,这毫无价值。第一个基本上只是偶然工作。这是使用方法引用的一种非常不直观的方式。做吧

    for (String s : philosophers)
    

    【讨论】:

    • 既然Iterable只有一个抽象方法,为什么不用FunctionalInterface注解呢?
    • @George 因为FunctionalInterface 旨在指定intent。 Iterable 的目的不是成为一个,它只是碰巧符合条件。见stackoverflow.com/questions/28166187/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多