在上一篇文章《java常用对象API中集合框架之TreeSet(上)》中智言已经把TreeSet类中的其中一种排序方式给大家做了一个详细的说明,同时配合相应的例子进行了阐述说明,不知道各位网友朋友们能够明白TreeSet类的用法,其实说白了就是自己定义了一个Person类并继承了Comparable类,然后在Person类里覆盖了CompareTo方法来进行自然排序。所以你可以根据不同的需求来对相应的需求进行必要排序即可。
但是如果说Person本身不是我们自己写的,也就是我们只是拿来用的,那么又如何使用TreeSet类来进行自然排序呢?
这个时候我们就需要用到TreeSet类的第二种排序方式:就是使用TreeSet集合类本身来进行排序。
例如:
我们可以在回顾一下上一篇的《java常用对象API中集合框架之TreeSet(上)》中我们的几个步骤。
1.同样,我们还是定义个Person类
public class Person{
private String name;
private int age;
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;
}
}
2.然后创建一个专用的自然排序类(比较器)ComparatorByName并实现Comparator接口,同时覆盖了compare方法
public class ComparatorByName implements Comparator{
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;
}
}
3.然后我们创建主函数TreeSetDemo
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new CompartorByName());
ts.add(new Person(“张三”,21));
ts.add(new Person(“李四”,22));
ts.add(new Person(“王五”,24));
ts.add(new Person(“赵六”,28));
Iterator it = ts.iterator();
while(it.hasNext()){
Person p=(Person)it.next();
System.out.println(p.getName()+”…”+p.getAge());
}
}
}
由此我们同样通过名字来进行了自然排序…
评论前必须登录!
注册