TreeSet 添加Student实体类数据 利用外部比较器排序

Student实体类如下所示:

package com.test.Test10;


import java.util.Comparator;

public class StudentWaiBuCompare{
    private int age;
    private String name;

    public int getAge() {
        return age;
    }

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


    public String getName() {
        return name;
    }

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

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

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }


}
//外部比较器定义
class BiJiao implements Comparator {

    @Override
    public int compare(StudentWaiBuCompare o1, StudentWaiBuCompare o2) {
        //return 0;
        return o1.getName().compareTo(o2.getName());
    }
}

测试类如下所示:
package com.test.Test10;

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

public class Test03WaiBuCompare {
    public static void main(String[] args) {
        //创建一个TreeSet
        //利用外部比较器,必须自己指定
        Comparator com = new BiJiao();
        TreeSet ts = new TreeSet<>(com); //一旦指定外部比较器,那么就会按照外部比较器来比较
        ts.add(new StudentWaiBuCompare(10,"elili"));
        ts.add(new StudentWaiBuCompare(8,"blili"));
        ts.add(new StudentWaiBuCompare(4,"alili"));
        ts.add(new StudentWaiBuCompare(9,"clili"));
        ts.add(new StudentWaiBuCompare(10,"elili"));
        ts.add(new StudentWaiBuCompare(1,"dlili"));
        System.out.println(ts.size()); //放了6个数据,出来了5个,重复的删除了
        System.out.println(ts);        //[Student{age=4, name='alili'}, Student{age=8, name='blili'}, Student{age=9, name='clili'}, Student{age=1, name='dlili'}, Student{age=10, name='elili'}]  按照name值的升序进行排列了
    }
}

你可能感兴趣的:(java,java,开发语言)