Question:
In Java, when using lambda expressions, is there a way to compare them for equality?
Answer:
From a Specification Perspective:
The language specification guarantees only that evaluating a lambda expression will result in an instance of a class that implements the target functional interface. However, it provides no guarantees about the identity or aliasing of these instances.
From an Implementation Perspective:
Current Java implementations establish a 1:1 relationship between the synthetic classes used to implement lambdas and their capture sites. If the same lambda is evaluated at the same capture site without capturing any variables, the same instance is produced and can be compared using reference equality (==).
For serializable lambdas, their state can be easily retrieved, but at the cost of decreased performance and security.
Challenges with Comprehensive Equality:
It's generally not feasible to determine if two lambdas with the same functional interface and behavior function are equal because:
Current Capabilities and Limitations:
Method references may have customizable equality definitions in the future to allow their use as listeners.
The Java Expert Group considered exposing information for more selective equals/hashCode and descriptive toString methods for lambdas. However, they decided against it due to the potential performance impact on the majority of users.
In terms of toString, no definitive conclusion was reached, but arguments were made for both sides, leaving the possibility of revisiting this issue in the future.
The above is the detailed content of Can Lambda Expressions Be Compared for Equality in Java?. For more information, please follow other related articles on the PHP Chinese website!