18-Map集合-08-常用对象API(集合框架-Map集合-TreeMap存储自定义对象)

package cn.itcast.bean;

public class Person {

	private String name;
	private int age;

	public Person() {
		super();

	}

	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

//	@Override
//	public int compareTo(Object o) {
//		
//		if(!(o instanceof Person))
//			throw new ClassCastException("类型错误");
//		Person p = (Person)o;
//		int temp=this.age-p.age;
//		return temp==0?this.name.compareTo(p.name):temp;
//	}
	
	

}

====================================分割线===================================

package cn.itcast.bean;

public class Student extends Person{
	
	public Student(String name,int age){
		
		super(name,age);
	}

}

====================================分割线===================================

package cn.itcast.comparator;


import java.util.Comparator;


import cn.itcast.bean.Person;


public class ComparatorByName implements Comparator<Object>{



@Override
public int compare(Object o1, Object o2) {

Person p1=(Person)o1;
Person p2=(Person)o2;
int temp=p1.getName().compareTo(p2.getName());
return temp==0?p1.getAge()-p2.getAge():temp;
}


}

====================================分割线===================================

package cn.itcast.treemap.demo;


import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;


import cn.itcast.bean.Student;
import cn.itcast.comparator.ComparatorByName;


public class TreeMapDemo {


public static void main(String[] args) {


TreeMap<Student, String> tm = new TreeMap<Student, String>(new ComparatorByName());


tm.put(new Student("lisi",38), "北京");
tm.put(new Student("zhaoliu", 24), "上海");
tm.put(new Student("xiaoqiang", 31), "沈阳");
tm.put(new Student("wangcai", 28), "大连");
tm.put(new Student("zhaoliu", 24), "铁岭");


Set<Map.Entry<Student, String>> s1 = tm.entrySet();

Iterator<Map.Entry<Student, String>> it = s1.iterator();

while (it.hasNext()) {
Map.Entry<Student, String> me = it.next();
Student key = me.getKey();
String value = me.getValue();
System.out.println(key.getName() + ":" + key.getAge() + "---"
+ value);


}
}


}

你可能感兴趣的:(18-Map集合-08-常用对象API(集合框架-Map集合-TreeMap存储自定义对象))