首先hashmap是不具备排序功能的。
对于treeMap的排序,所谓的排序指的是对key的排序,有两种方式:
1、往treeMap中存放的元素有比较性,常做的操作是元素对应的类实现Compareable,如:
treeMap集合中存放学生,学生类实现Compareable接口,按照学生年龄排序,年龄相同时按照姓名自然顺序排序
TreeSet<Student> tr = new TreeSet<Student>();
tr.add(new Student("lisi01",11));
tr.add(new Student("lisi02",12));
class Student implements Comparable{
...
//实现compareTo方法
public int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("类型不匹配");
Student s = (Student)obj;
System.out.println(this.name+"..."+s.name);
int num = new Integer(this.age).compareTo(new Integer(s.age));
if(num==0)
return this.name.compareTo(s.name);
return num;
}
...
}
public int compare(Object o1, Object o2){
Student s1 = (Student)o1;
Student s2 = (Student)o2;
int n = new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
if(n==0){
return new Integer(s1.getName()).compareTo(new Integer(s2.getName()));
}
return n;
}
}