Java相等判断

121 阅读1分钟
/**
 * == 用来比较地址是否相等
 * equals 用来比较内容是否相等
 *
 * 如果两个对象的equals相等,则hashCode()也应该相等
 * 反之,则不成立
 *
 */

当对象作为hashmap的key时,需要重写equals和hashCode

public class RequestHttpEntityKey {

    private String url;
    private HttpMethod method;


    @Override
    public boolean equals(Object o) {
        if (this == o) return true; // 地址相等,必是同一个对象
        if (o == null || getClass() != o.getClass()) return false;
        RequestHttpEntityKey httpReq = (RequestHttpEntityKey) o;
        return Objects.equals(url, httpReq.url) && method == httpReq.method;
    }

    @Override
    public int hashCode() {
        return Objects.hash(url, method);
    }
}