简体   繁体   English

Java 如何处理方法推断 Lambda 表达式作为方法参数?

[英]How Java process Method Inference Lambda Expression as method parameter?

In code below, method inference iF::apply is put into a Map in class Context .在下面的代码中,方法推断iF::apply被放入Map Context中的 Map 中。

But when using get method on the Map with iF::apply , we get null .但是当通过iF::applyMap上使用get方法时,我们得到null Why?为什么?

Here is the debug info with IDEA:这是 IDEA 的调试信息:

在此处输入图像描述

Below is the code:下面是代码:

    public void test() {
        Context context = new Context();
        IF iF = new IF();
        context.put(iF::apply, 100);
        Integer v = context.get(iF::apply);
        System.out.println(v);
    }

class IF implements Function<String, Integer> {
    @Override
    public Integer apply(String s) {
        return 200;
    }
}

class Context {
    private Map<Function, Object> items = new HashMap<>();

    public <T, R> void put(Function<T, R> name, R value) {
        items.put(name, value);
    }

    public <T, R> R get(Function<T, R> name) {
        return (R)items.get(name);
    }
}

Your code contains two iF::apply Method Reference Expressions .您的代码包含两个iF::apply 方法引用表达式 Each time it creates a new Function<String, Integer> instance.每次它创建一个新的Function<String, Integer>实例。

Since those instances don't override equals() and hashCode() they are not really usable as keys in a HashMap .由于这些实例不会覆盖equals()hashCode()它们实际上不能用作HashMap中的键。 If you want to retrieve the entry that is already in the map you must use the same instance.如果要检索 map 中已有的条目,则必须使用相同的实例。

That these are different instances can be seen from your screenshot:从您的屏幕截图中可以看出这些是不同的实例:

  • the key in the map is {App$lambda@648} map 中的密钥是{App$lambda@648}
  • the argument that is provided to retrieve the entry is {App$lambda@644}为检索条目提供的参数是{App$lambda@644}

These names in the debug view are built using the simple classname ( App$lambda ) followed by @ followed by some unique identifier per object that the debugger encountered.调试视图中的这些名称是使用简单的类名 ( App$lambda ) 构建的,后跟@后跟调试器遇到的每个 object 的一些唯一标识符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM