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:
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)

0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.