处理TreeSet集合比较方式问题,完成比较方式
【问题】
TresSet集合存储元素需要自然顺序或者【比较方式】,Test类没有比较方式,所以上一章的示例中最后显示了异常,那么如何完成比较方式,顺利的把元素存入TreeSet集合中呢?
【解决】
<1>Test类遵从
Comparable<T>
接口,实现compateTo()
方法public int compareTo(T t);
<2>给TreeSet添加插件,比较方式插件,在创建TreeSet对象过程中,传入一个
Comparator<T>
接口实现类对象,实现compare()
方法;public int compare(T o1, T o2);
//向TreeSet集合中添加一个自定义对象元素
//实现Comparable<T>接口处理比较方式问题
//实现之后就可以进行比较
//因为明确了是Test类,所以就是Comparable<Test>
public class Test implements Comparable<Test>{
//该方法返回值是一个int类型
//如果返回值 负数 <0 说明前者数据小于后者数据
//如果返回值 正数 >0 说明前者数据大于后者数据
//如果返回值 等于0 =0 说明前者数据等于后者数据 后者无法进行添加 因为set接口不允许重复
//该方法会在当前的Test类中需要排序的时候自行进行调用;
//比如TreeSet结构添加过程中,就调用compareTo方法进行比较判断;
@Override
public int compareTo(Test o){
//重写一下 拿年龄来作为判断标准
return o.age - this.age;
}
//成员变量
private String name;
private Integer age;
private String sex;
//无参构造方法
public Test(){}
//有参构造方法
public Test(String name,Integer age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
public static void main(String[] args) {
//创建一个TreeSet集合 存放Test类对象数据
//有了实现Comparable类之后 可以进行比较
TreeSet<Test> set2 = new TreeSet<>();
//TreeSet每一个存储的元素都需要有对应的比较方式或者自然顺序;
//现在的顺序是依据年龄来的,如果年龄相同就无法存入;
set2.add(new Test("小哈",10,"男"));
set2.add(new Test("小花",8,"女"));
set2.add(new Test("小金",7,"男"));
set2.add(new Test("小蓝",7,"男"));
set2.add(new Test("小黄",9,"男"));
System.out.println(set2);
}
}
实现comparator<T>
接口 向TreeSet集合中存入元素
@Data
public class Test{
//成员变量
private String name;
private Integer age;
private String sex;
//无参构造方法
public Test(){}
//有参构造方法
public Test(String name,Integer age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
}
//实现Comparator<T> 接口并重写compare方法
//实现Comparator接口属于自定义比较器
//自定义比较器并不存在于Test类被调用类里面,而是存在于调用类里
class Demo13 implements Comparator<Test>{
//重写compare(T t1,T t2)方法
//核心还是 o1.getAge() - o2.getAge()
//只不过在一个方法cmopare内
//方法又在一个类中
//类想要执行该方法,需要一个类对象
@Override
public int compare(Test o1, Test o2) {
return o1.getAge() - o2.getAge();
}
public static void main(String[] args) {
Demo13 demo13 = new Demo13();
//如果一个方法的参数是一个接口该怎么处理???
//创建他的实现类的对象进行传入
test(demo13);
//将创建的自定义构造器通过集合的构造方法进行传入
//后面的元素就可以添加进入集合中
TreeSet treeSet = new TreeSet(demo13);
treeSet.add(new Test("小哈",10,"男"));
treeSet.add(new Test("小花",8,"女"));
treeSet.add(new Test("小金",7,"男"));
}
public static void test(Comparator<Test> test){
int i = test.compare(new Test("小哈",10,"男"),
new Test("小黄",9,"男"));
System.out.println(i);
}
}