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

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

使用哪一个

== 和 equals 都可以

代码

public class MyTest {
    @Test
    public void test03() {

        System.out.println(OperatorTypeEnum.ADD == OperatorTypeEnum.ADD);
        System.out.println(OperatorTypeEnum.ADD.equals(OperatorTypeEnum.ADD));
        CustomerDTO customerDTO = new CustomerDTO();
        customerDTO.setName("测试");
        customerDTO.setOperatorTypeEnum(OperatorTypeEnum.ADD);
        System.out.println(customerDTO.getOperatorTypeEnum() == OperatorTypeEnum.ADD);
        System.out.println(customerDTO.getOperatorTypeEnum().equals(OperatorTypeEnum.ADD));
    }

}

enum OperatorTypeEnum {
    ADD(0, "添加"),
    UPDATE(1, "更新");
    private Integer code;

    private String message;

    OperatorTypeEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

class CustomerDTO {

    private String name;

    private OperatorTypeEnum operatorTypeEnum;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public OperatorTypeEnum getOperatorTypeEnum() {
        return operatorTypeEnum;
    }

    public void setOperatorTypeEnum(OperatorTypeEnum operatorTypeEnum) {
        this.operatorTypeEnum = operatorTypeEnum;
    }
}

打印结果

true
true
true
true

再看下枚举调用equals的实现

  /**
     * Returns true if the specified object is equal to this
     * enum constant.
     *
     * @param other the object to be compared for equality with this object.
     * @return  true if the specified object is equal to this
     *          enum constant.
     */
    public final boolean equals(Object other) {
        return this==other;
    }

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

所以效果是一样的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值