Java-TreeSet集合排序的第二种方式

/*
 * TreeSet集合排序的第二种方式:
 *                 当元素自身不具备比较性时,或者具备的比较性不是所需要的
 *                 这时就需要让集合自身具备比较性
 *                 定义了比较器,将比较器对象作为参数传递给TreeSet集合的构造函数
 *
 *                 当两种排序都存在时,以比较器为主。
 *                 定义一个类,实现Comparator接口,覆盖compare方法
 */

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

class Student1 implements Comparable{//该接口强制让学生具备比较性
    private String name;
    private int age;
    
    Student1(String name,int age){
        this.name = name;
        this.age = age;
    }
    public int compareTo(Object obj) {
        if(!(obj instanceof Student1))
            throw new RuntimeException("不是学生对象");
        
        
        Student1 s = (Student1)obj;
//        System.out.println(this.name+"===="+s.name);
        if(this.age>s.age) {
            return 1;
        }
        if(this.age==s.age) {
            return this.name.compareTo(s.name);
        }
        return -1;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
}

public class TreeSetDemo1 {

    public static void Sop(Object obj) {
        System.out.println(obj);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TreeSet ts = new TreeSet(new MyCompare());
        
        ts.add(new Student1("lisa02",20));
        ts.add(new Student1("lisa05",10));
        ts.add(new Student1("lisa02",30));
        ts.add(new Student1("lisa04",30));
        ts.add(new Student1("lisa03",30));
        
        Iterator it = ts.iterator();
        
        while(it.hasNext()) {
            Student1 stu = (Student1)it.next();
            Sop(stu.getName()+"----"+stu.getAge());
        }

    }

}

class MyCompare implements Comparator{//模拟比较器
    public int compare(Object o1,Object o2) {
        Student1 s1 = (Student1)o1;
        Student1 s2 = (Student1)o2;
        
        int num = s1.getName().compareTo(s2.getName());
        if(num==0) {
            return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
            
//            if(s1.getAge()>s2.getAge()) {
//            return 1;
//            }
//            if(s1.getAge()==s2.getAge()) {
//                return 0;
//            }
//            return -1;
        }
        return num;
    }
}

猜你喜欢

转载自blog.csdn.net/Lydia233/article/details/102655528