关于枚举值使用 == 还是 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 方法 调用的 还是 == 进行比较
所以效果是一样的
还没有评论,来说两句吧...