【问题标题】:The target type of this expression must be a functional interface in java这个表达式的目标类型必须是java中的函数接口
【发布时间】:2018-04-12 10:27:03
【问题描述】:
lmod.forEachWithIndex( (e, i) -> lmod.set(i, e*2));

我收到错误:

类型 XList 中的 forEachWithIndex(Object) 方法不适用于参数 (( e, i) -> {}) 此表达式的目标类型必须是函数式接口

这是什么意思?我该如何解决?

 import java.util.*;

public class Main {

public static void main(String[] args) {

XList<Integer> lmod = XList.of(  new  Integer[]  {1,2,8, 10, 11, 30, 3, 4});  
lmod.forEachWithIndex( (e, i) -> lmod.set(i, e*2));
System.out.println(lmod);

}}

 import java.util.ArrayList; 
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.List; 
 import java.util.Set;
 import java.util.function.Consumer;

public class XList implements Collection, Consumer {

public List<T> list = new ArrayList<T>();

public XList(T[] ints) {

    for( int i = 0; i < ints.length; i++)
        list.add(ints[i]);

}


public static XList<Integer> of(Integer[] ints) {

    return new XList(ints);
}

  public void forEachWithIndex(Object object) {

  }

   @Override
   public void accept(T t) {

   }

}

我添加了函数接口Consumer,但我仍然不知道下一步该怎么做

【问题讨论】:

  • forEachWithIndex 必须有一个函数接口作为其参数类型(不是对象),它与您尝试传递给它的 lambda 表达式 (e, i) -&gt; lmod.set(i, e*2) 匹配。

标签: java function lambda interface expression


【解决方案1】:

您可以通过以下代码绕过您的错误,但我强烈建议您将 forEachWithIndex 参数从 Object 修改为 BiConsumer
喜欢

public void forEachWithIndex(BiConsumer biConsumer) {}

如果您仍然想严格执行,这里的代码可能会对您有所帮助。

BiConsumer biConsumer = (e, i) -> lmod.set(i, e*2);
lmod.forEachWithIndex(biConsumer);

另外,我相信当您将 Bi​​Consumer 传递给您将在内部使用它的方法时,在这种情况下,如果您将参数设置为 Object,则需要执行 casting

【讨论】:

  • 我使用了代码 BiConsumer biConsumer = (e, i) -> lmod.list.set(i, e*2); lmod.forEachWithIndex(biConsumer);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多