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);
}
}
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:
{App$lambda@648}
{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.