1 the cause
Enumerations are often used in project development. Will comparisons of enumerations, like those of objects, result in identical properties but false comparisons?
2 Solution
There are three ways to compare enumerations:
- compareTo()
- equals()
- = =
2.1 compareTo ()
This method returns the difference between enumerations, directly to the code (W3Cschool):
enum Level {
LOW, MEDIUM, HIGH, URGENT;
}
public class Main {
public static void main(String[] args) {
Level s1 = Level.LOW;
Level s2 = Level.URGENT;
int diff = s1.compareTo(s2);
// diff = s1 - s2 = 0 - 3 = -3System.out.println(diff); }}Copy the code
When the return value is 0, both enumerations are the same
2.2 the equals ()
As with normal object comparisons, the same enumeration returns true
2.3 = =
The same enumeration returns true
3 Principle Analysis
Most people, like me, have questions about the approach in 2.2
The root of the problem lies in the way we generate enumerations. In Java we typically create enumerations like this:
TestEnum one = TestEnum.ONE
TestEnum two = TestEnum.ONE
Copy the code
Using equals() between two newly generated objects must result in false
But instead of using new to generate the enumeration, we get the reference object directly, so using equals() naturally returns true