首先我们创建一个类
public class People { private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public People() { super(); } public People(String name, String address) { super(); this.name = name; this.address = address; } @Override public String toString() { return "People [name=" + name + ", address=" + address + "]"; } }
该类没有重写hashcode和equals方法
下面我们进行比较
public static void main(String[] args) { People p1 = new People("a", "A"); People p2 = new People("a", "A"); People p3 = new People("b", "B"); System.err.println(p1); System.err.println(p2); System.err.println(p3); System.err.println(p1.equals(p2)); System.err.println(p1 == p2); System.err.println(p1.equals(p3)); System.err.println(p1 == p3); }
结果为:
说明如果没有重写equals()方法,则equals和==比较的都是地址。每生成一个对象,虚拟机都会重新生成一个地址,因此比较结果都为false
我们加上hashcode和equals方法
public class People { private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public People() { super(); } public People(String name, String address) { super(); this.name = name; this.address = address; } @Override public String toString() { return "People [name=" + name + ", address=" + address + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; People other = (People) obj; if (address == null) { if (other.address != null) return false; } else if (!address.equals(other.address)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
再次运行实例,结果为:
说明如果重写equals()方法,则==比较的是地址,equals比较的是对象中的内容