_005_Java试题_为什么说hashCode值相等,两个对象不一定相等?(重写了equals和hashCode方法)

为什么说hashCode值相等,两个对象不一定相等?(重写了equals和hashCode方法)

import java.util.HashSet;
import java.util.Iterator;

import org.junit.Test;

public class Customer {
	
	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 Customer(String name, String address) {
		this.name = name;
		this.address = address;
	}
	
	@Override
	public int hashCode() {
		return 1;
	}
	@Override
	public boolean equals(Object obj) {
		System.out.println("hello,现在是equals方法");
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Customer other = (Customer) 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;
	}
	
	
	
	@Override
	public String toString() {
		return "Customer [name=" + name + ", address=" + address + "]";
	}
	
	
	public static void main(String[] args) {
		HashSet hashSet = new HashSet<>();
		System.out.println("第一次添加");
		hashSet.add(new Customer("1", "A"));
		System.out.println("第二次添加");
		hashSet.add(new Customer("2", "0"));
		System.out.println("第三次添加");
		hashSet.add(new Customer("2", "1"));
		
		Iterator iterator = hashSet.iterator();
		
		System.out.println("哈希值:");
		System.out.println(new Customer("1", "A").hashCode());
		System.out.println(new Customer("2", "a").hashCode());
		System.out.println(new Customer("2", "1").hashCode());
		
		System.out.println("遍历:");
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
			
		}
	}
}


输出:

第一次添加
第二次添加
hello,现在是equals方法
第三次添加
hello,现在是equals方法
hello,现在是equals方法
哈希值:
1
1
1
遍历:
Customer [name=1, address=A]
Customer [name=2, address=0]
Customer [name=2, address=1]

 比如:

Customer a=Customer(“aaa”, "bbb");

Customer b=Customer(“bbb”, "aaa");

 

虽然a和b是两个不同的对象,但是它们的hashcode值相等,这就是重载hashcode方法可能存在的缺陷。

你可能感兴趣的:(_002_Java习题)