Reputation: 941
If an enum constant is compared with something else, is it permissible to use ==
in place of the equals
method?
Example (User
implements the interface IUser
):
IUser peter = User.PETER;
if (User.PETER == peter) {
// do something
}
Upvotes: 0
Views: 85
Reputation: 5207
In your code we assume that your enumeration User implements interface IUser. Otherwise the code IUser peter = User.PETER; would compile.
Yes, it is safe. Because in the class loader there can be a single instance of each enumeration. This means, there can be only a single instance of each enumeration value. These values cannot be created by some other mechanism. That's why if there are two variables representing the same enumeration value, it must be the same instance. That's why simple comparison by == is sufficient.
Upvotes: 1