enum Drill{
ATTENTION("Attention!"), AT_EASE("At Ease");
private String str;
private Drill(String str){
this.str = str;
}
public String toString(){
return str;
}
}
public class EnumExample {
public static void main(String[] args) {
Drill d1= Drill.valueOf("ATTENTION");
Drill d2= Drill.valueOf("ATTENTION");
**System.out.println(d1.equals(d2));//TRUE
System.out.println(d1==d2);//TRUE**
System.out.println(Drill.ATTENTION.equals(Drill.valueOf("ATTENTION")));
System.out.println(Drill.ATTENTION.equals(Drill.AT_EASE));//FALSE
System.out.println(Drill.ATTENTION==Drill.valueOf("ATTENTION"));//TRUE
System.out.println(Drill.ATTENTION==Drill.AT_EASE);//FALSE
}
}
Enum behaviour while using == and equals() seems to be same. According to my knowledge, == just check references. Therefore d1 == d2 should be FALSE. Can anyone explain this behavior why is is TRUE?
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.
equals() method. equals() method returns true if the specified object is equal to this enum constant. Using == operator. The == operator checks the type and makes a null-safe comparison of the same type of enum constants.
The java. lang. Enum. clone() method guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.
CA1069: Enums should not have duplicate values.
==
should work fine with enums because there aren't multiple references of a given enum item; there's just one. The Java Language Specification section on enum types, 8.9 states that they are implicitly static and final and so can only be created once.
You are comparing enum constants. This means that for each enum constant, there is a single instance created.
This
enum Drill{
ATTENTION("Attention!"), AT_EASE("At Ease");
...
}
is more or less equivalent to
final class Drill {
public static final Drill ATTENTION = new Drill("Attention!") {};
public static final Drill AT_EASE = new Drill("At Ease") {};
...
}
The valueOf
method
/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type. (Extraneous whitespace
* characters are not permitted.)
*
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);
returns the value of instance referred to by the variable whose name equals the specified String
value.
So
Drill.valueOf("ATTENTION") == Drill.ATTENTION
for every invocation of valueOf
with that String
value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With