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

后端 未结 8 673
暖寄归人
暖寄归人 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条回答
  • 2020-12-13 12:24

    Note that there is problem when transfering enum via RMI/IIOP. See this thread:

    http://www.velocityreviews.com/forums/t390342-enum-equality.html

    0 讨论(0)
  • 2020-12-13 12:27

    Enums are a great place to jam polymorphic code.

    enum Rounding {
      ROUND_UP {
        public int round(double n) { ...; }
      },
      ROUND_DOWN {
        public int round(double n) { ...; }
      };
    
      public abstract int round(double n);
    }
    
    int foo(Rounding roundMethod) {
      return roundMethod.round(someCalculation());
    }
    
    int bar() {
      return foo(Rounding.ROUND_UP);
    }
    
    0 讨论(0)
提交回复
热议问题