PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 3, 2022

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

 November 03, 2022     inference, java, lambda, methods     No comments   

Issue

In code below, method inference iF::apply is put into a Map in class Context.

But when using get method on the Map with iF::apply, we get null. Why?

Here is the debug info with IDEA:

enter image description here

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);
    }
}

Solution

Your code contains two iF::apply Method Reference Expressions. Each time it creates a new Function<String, Integer> instance.

Since those instances don't override equals() and hashCode() they are not really usable as keys in a HashMap. If you want to retrieve the entry that is already in the map you must use the same instance.

That these are different instances can be seen from your screenshot:

  • the key in the map is {App$lambda@648}
  • the argument that is provided to retrieve the entry is {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.



Answered By - Thomas Kläger
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing