JAVA之Map之
TreeMap键为自定义对象
--------------------------------------------
TreeMap
唯一性和强制排序性。。
比HashMap多一个强制排序的功能
--------------------------------------------
TreeMap
键:Student 【自定义对象】
值:String
---------------Student-----------------------
package com.lyMapTreeMap;
/**
* TreeMap必须实现Comparable接口,才能比较
* @author Jack
*
*/
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}
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(Student o) {
int num = this.getAge() - o.getAge();
int num2 = num == 0? this.getName().compareTo(o.getName()):num;
return num2;
}
}
·····················测试·······················
package com.lyMapTreeMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* TreeMap:
* 键:Student【自定义对象】
* 值:String
*
* @author Jack
*/
public class TreeMapDemo {
public static void main(String[] args) {
// 创建TreeMap集合
Map<Student,String> tm = new TreeMap<Student,String>();
// 创建学生对象
Student s1 = new Student("学士1", 21 );
Student s2 = new Student("学士2", 22 );
Student s3 = new Student("学士3", 23 );
Student s4 = new Student("学士4", 24 );
Student s5 = new Student("学士3", 23 );
tm.put(s1, "唐朝");
tm.put(s2, "宋朝");
tm.put(s3, "元朝");
tm.put(s4, "明朝");
tm.put(s5, "清朝");
Set<Student> set = tm.keySet();
for(Student key : set){
String value = tm.get(key);
System.out.println(key.getName() + "---"+key.getAge() +"--"+value);
}
}
}
·········结果············
学士1---21--唐朝
学士2---22--宋朝
学士3---23--清朝
学士4---24--明朝
··························