关于枚举值使用 == 还是 equals 比较

桃扇骨 2023-05-31 07:08 37阅读 0赞

关于枚举值使用 == 还是 equals比较

使用哪一个

== 和 equals 都可以

代码

  1. public class MyTest {
  2. @Test
  3. public void test03() {
  4. System.out.println(OperatorTypeEnum.ADD == OperatorTypeEnum.ADD);
  5. System.out.println(OperatorTypeEnum.ADD.equals(OperatorTypeEnum.ADD));
  6. CustomerDTO customerDTO = new CustomerDTO();
  7. customerDTO.setName("测试");
  8. customerDTO.setOperatorTypeEnum(OperatorTypeEnum.ADD);
  9. System.out.println(customerDTO.getOperatorTypeEnum() == OperatorTypeEnum.ADD);
  10. System.out.println(customerDTO.getOperatorTypeEnum().equals(OperatorTypeEnum.ADD));
  11. }
  12. }
  13. enum OperatorTypeEnum {
  14. ADD(0, "添加"),
  15. UPDATE(1, "更新");
  16. private Integer code;
  17. private String message;
  18. OperatorTypeEnum(Integer code, String message) {
  19. this.code = code;
  20. this.message = message;
  21. }
  22. public Integer getCode() {
  23. return code;
  24. }
  25. public void setCode(Integer code) {
  26. this.code = code;
  27. }
  28. public String getMessage() {
  29. return message;
  30. }
  31. public void setMessage(String message) {
  32. this.message = message;
  33. }
  34. }
  35. class CustomerDTO {
  36. private String name;
  37. private OperatorTypeEnum operatorTypeEnum;
  38. public String getName() {
  39. return name;
  40. }
  41. public void setName(String name) {
  42. this.name = name;
  43. }
  44. public OperatorTypeEnum getOperatorTypeEnum() {
  45. return operatorTypeEnum;
  46. }
  47. public void setOperatorTypeEnum(OperatorTypeEnum operatorTypeEnum) {
  48. this.operatorTypeEnum = operatorTypeEnum;
  49. }
  50. }

打印结果

  1. true
  2. true
  3. true
  4. true

再看下枚举调用equals的实现

  1. /**
  2. * Returns true if the specified object is equal to this
  3. * enum constant.
  4. *
  5. * @param other the object to be compared for equality with this object.
  6. * @return true if the specified object is equal to this
  7. * enum constant.
  8. */
  9. public final boolean equals(Object other) {
  10. return this==other;
  11. }

重写了equals 方法 调用的 还是 == 进行比较

所以效果是一样的

发表评论

表情:
评论列表 (有 0 条评论,37人围观)

还没有评论,来说两句吧...

相关阅读