Java一步一脚印—HashMap

import java.util.*;
class StudentData{
	private int ID;
	private String name;
	private String sex;
	private int age;
	public StudentData(int ID,String name, String sex, int age){
		this.ID=ID;
		this.name=name;
		this.sex=sex;
		this.age=age;
	}
	public String toString(){
	return ID+" "+name+" "+sex+" "+age;
	}
	public boolean equals(Object o)
	{
		StudentData s=(StudentData)o;
		return this.ID==s.ID&&this.name.equals(s.name)&&this.sex.equals(s.sex)&&this.age==s.age;
	}
	public int hashCode(Object o){
		return ID*age*this.name.hashCode()*this.sex.hashCode();
	}
}
public class Test3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashMap hm=new HashMap();
		hm.put(01,new StudentData(01,"李华","男",20));
		hm.put(02,new StudentData(02,"小红","女",19));
		hm.put(03,new StudentData(03,"小刚","男",26));
		hm.put(01,new StudentData(01,"李华","男",20));
		Set s=hm.keySet();
		Iterator it=s.iterator();
		while(it.hasNext())
		{
			Integer Key=(Integer)it.next();
			System.out.println(hm.get(Key));
		}
	}

}
从中可以看出HashMap和HashSet有很多相似的地方,都需要重写equals()和hashCode()方法,这样最根本的原因就是避免重复存储,而底层就是为了确定他们的存储的方法,下面将详细讲解低层实现。

你可能感兴趣的:(java)