Java Reference
In-Depth Information
-3
Suppose you have another enum called BasicColor .
public enum BasicColor {
RED, GREEN, BLUE;
}
The following snippet of code will not compile because it tries to compare the two enum constants, belonging to
different enum types:
int diff = BasicColor.RED.compareTo(Severity.URGENT); // A compile-time error
You can use the equals() method of the Enum class to compare two enum constants for equality. An enum
constant is equal only to itself. Note that the equals() method can be invoked on two enum constants of different
types. If the two enum constants are from different enum types, the method returns false .
Severity s1 = Severity.LOW;
Severity s2 = Severity.URGENT;
BasicColor c = BasicColor.BLUE;
System.out.println(s1.equals(s1));
System.out.println(s1.equals(s2));
System.out.println(s1.equals(c));
true
false
false
You can also use the equality operator ( == ) to compare two enum constants for equality. Both operands to the ==
operator must be of the same enum type. Otherwise, you get a compile-time error.
Severity s1 = Severity.LOW;
Severity s2 = Severity.URGENT;
BasicColor c = BasicColor.BLUE;
System.out.println(s1 == s1);
System.out.println(s1 == s2);
// A compile-time error. Cannot compare Severity and BasicColor enum types
//System.out.println(s1 == c);
true
false
Nested Enum Types
You can have a nested enum type declaration. You can declare a nested enum type inside a class, an interface, or
another enum type. Nested enum types are implicitly static . You can also declare a nested enum type static
explicitly in its declaration. Since an enum type is always static , whether you declare it or not, you cannot declare a
 
Search WWH ::




Custom Search