hashcode、equals、HashMap间的关系

1、从Object说起

package com.hallo.collection;

public class ObjectDemo {

	public static void main(String[] args) {
		 
		Object o1 = new Object();
		Object o2 = new Object();
		
		//同一Object对象,hashCode永远相同
		assert(o1.hashCode() == o1.hashCode());
		//不同Object对象,hashCode永远不相同
		assert(o1.hashCode() != o2.hashCode());
		
		//不同对象equals返回false
		assert(!o1.equals(o2));
		
		System.out.println("end");
		
	}
}

输出:end

2、String类Demo

package com.hallo.collection;

public class StringDemo {

	public static void main(String[] args) {
		
		String str1 = "hello";
		String str2 = "hello";
		String str3 = new String("hello");
		
		//不同string对象(==不成立)保存相同字符串时,hashCode和equals返回相同
		assert(str1.hashCode() == str2.hashCode());
		assert(str1.equals(str2));
		assert(str2.hashCode() == str3.hashCode());
		assert(str2.equals(str3));
		
		System.out.println("end");
	}
}

输出:end

3、自定义类,重写hashcode、equals方法

package com.hallo.collection;

import java.util.HashMap;
import java.util.Map;

public class MyObject {

	private String name;
	
	public String getName() {
		return name;
	}

	public MyObject(String name) {
		this.name = name;
	}

	@Override
	public int hashCode() {
		//使用object类的方法
		return super.hashCode();
	}
	
	@Override
	public boolean equals(Object obj) {
		
		if(this == obj)
			return true;
		
		if(obj instanceof MyObject) {
			return ((MyObject) obj).getName().equals(this.getName());
		}
		
		return false;
	}
	
	public static void main(String[] args) {
		
		MyObject o1 = new MyObject("k1");
		MyObject o2 = new MyObject("k1");
		MyObject o3 = new MyObject("k3");
		
		Map myObjectMap = new HashMap();
		myObjectMap.put(o1, "o1");
		myObjectMap.put(o1, "o11");
		myObjectMap.put(o2, "o2");
		myObjectMap.put(o3, "o3");
		
		System.out.println(myObjectMap);
	}
	
}

输出:

{com.hallo.collection.MyObject@7852e922=o11,

com.hallo.collection.MyObject@70dea4e=o3,

com.hallo.collection.MyObject@4e25154f=o2}

你可能感兴趣的:(Java)