Application TreeMap collection ordered according to the student's age or name


/**
TreeMap练习

根据年龄排序。

根据姓名排序:

*/
import java.util.*;
class StuNameComparator implements Comparator<Student>
{
	//复写compare方法
	public int compare(Student s1,Student s2)
	{
		int num= s1.getName().compareTo(s2.getName());
		if (num==0)
		{
			return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
		}
		return num;
	}
}
class  TreeMapTest
{
	public static void main(String[] args) 
	{
		TreeMap<Student,String > tm=new TreeMap<Student,String >(new StuNameComparator());//TreeMap可以将比较器传递到其对象内
		
		
		
		tm.put(new Student("zhangsan01",24),"beijing");
		tm.put(new Student("zhangsan04",32),"shenzheng");
		tm.put(new Student("zhangsan03",23),"shenzheng");
		tm.put(new Student("zhangsan02",20),"shnghai");
		//tm.put(new Student("zhangsan03",32),"shenzheng");

		//使用entrySet遍历
		Set<Map.Entry<Student,String>> entryset=tm.entrySet();
		Iterator<Map.Entry<Student,String>> it=entryset.iterator();
		while (it.hasNext())
		{
			Map.Entry<Student,String> map=it.next();
			Student key=map.getKey();
			String value=map.getValue();
			System.out.println(key+"=="+value);
		}
	}
}
创建学生类,定义一个比较器。<pre name="code" class="java">class Student implements Comparable<Student>//比较学生
{
	private String name;
	private int age;
	Student(String name ,int age){
		this.name=name;
		this.age=age;
	}
	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;
	}
	public int hashCode(){
		return this.name.hashCode()+age*34;
	}
	public boolean equals(Object obj){
		//判断类型是否相同
		if (!(obj instanceof Student))
		{
			throw new ClassCastException("类型不同");
		}
		Student s=(Student)obj;
		return this.name.equals(s.name) && this.age==s.age;
	}
	

	public String toString(){
		return name+":"+age;
	}
	public void setName(String name){
		this.name=name;
	}
	public String getName(){
		return name;
	}
	public void setAge(int age){
		this.age=age;
	}
	public int getAge(){
		return age;
	}


}

 
Published 55 original articles · won praise 46 · views 110 000 +

Guess you like

Origin blog.csdn.net/Kern_/article/details/39545461