Map用法2

package mapDemo2;
import java.util.*;
class MapDemo2 
{
	public static void main(String[] args) 
	{
		HashMap<Student,String> hm=new HashMap<Student,String>();
		hm.put(new Student("zs",21),"beijing");
		hm.put(new Student("lisi",14),"tianjin");
		hm.put(new Student("wangwu",64),"guangdong");
		//keySet方法
		Set<Student> set=hm.keySet();
		Iterator<Student> it=set.iterator();
		while(it.hasNext())
		{
			Student sd=it.next();
			String addr=hm.get(sd);
			System.out.println(sd.getName()+"-----"+addr);
		}
		//entrySet方法
		Set<Map.Entry<Student,String>> s=hm.entrySet();
		Iterator<Map.Entry<Student,String>> it1=s.iterator();
		while(it1.hasNext())
		{
			Map.Entry<Student,String> me=it1.next();
			Student stu=me.getKey();
			String addre=me.getValue();
			System.out.println(stu.getName()+"----------"+addre);
		}
	}
}
//Student類
class Student implements Comparable<Student>
{
	private String name;
	private int age;

	Student(String name,int age)
	{
		this.name=name;
		this.age=age;
	}
	//獲取姓名
	public String getName()
	{
		return name;
	}
	//獲取年齡
	public int getAge()
	{
		return age;
	}
	//重寫hashCode()
	public int hashCode(Object obj)
	{
		return name.hashCode()+age*10;
	}
	//重寫equals()
	public boolean equals(Object obj)
	{
		if(!(obj instanceof Student))
			throw new ClassCastException("類型不匹配");
		Student sd=(Student)obj;
		return this.name.equals(sd.name) && this.age==sd.age;
	}
	//重寫compareTo()
	public int compareTo(Student s)
	{
		int num=new Integer(this.age).compareTo(new Integer(s.age));
		if(num==0)
			return this.name.compareTo(s.name);
		return num;
	}
}

發佈了69 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章