Is it OK to use == on enums in Java?

后端 未结 8 698
暖寄归人
暖寄归人 2020-12-13 11:48

Is it OK to use == on enums in Java, or do I need to use .equals()? In my testing, == always works, but I\'m not sure if I\'m guarant

8条回答
  •  猫巷女王i
    2020-12-13 12:10

    Yes, == is fine - there's guaranteed to be just a single reference for each value.

    However, there's a better way of writing your round method:

    public int round(RoundingMode roundingMode) {
      switch (roundingMode) {
        case HALF_UP:
           //do something
           break;
        case HALF_EVEN:
           //do something
           break;
        // etc
      }
    }
    

    An even better way of doing it is to put the functionality within the enum itself, so you could just call roundingMode.round(someValue). This gets to the heart of Java enums - they're object-oriented enums, unlike the "named values" found elsewhere.

    EDIT: The spec isn't very clear, but section 8.9 states:

    The body of an enum type may contain enum constants. An enum constant defines an instance of the enum type. An enum type has no instances other than those defined by its enum constants.

提交回复
热议问题