列挙値の使用について=それともequalsの比較ですか?

2146 ワード

列挙値の使用について=それとも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メソッドの呼び出しを書き直しましたか?それとも=比較しますか?
だから効果は同じです.