TreeSet、Comparator的结合应用

本文介绍Java中TreeSet的使用方法,包括如何自定义比较器实现元素的排序,并提供了一个具体的例子,展示了如何根据Student对象的年龄属性进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TreeSet是一个集合类,用法很普遍,下面一些代码段供大家参考

定义TreeSet对象

TreeSet tset=new TreeSet();

添加数据信息

tset.add(new String("1"));

tset.add(new String("2"));

tset.add(new String("3"));

遍历所有信息:

Iterator it=tset.iterator();

while(it.hasnext()){

  System.out.println(it.next());

}

如果我们想要排序,添加tset.comparator()方法即可实现自然排序,但是如果我们希望,我们自己定义进行排序呢?

那就要用到我们自己定义的比较器,需要我们实现Comparator这个接口类

//定义一个比较器
class MyCompare implements Comparator<Student>{


 @Override
 public int compare(Student o1, Student o2) {
  Student upStu1 = (Student)o1;
  Student upStu2 = (Student)o2;
  int result=0;
  if(upStu1.getAge()>upStu2.getAge()){
   result=1;
  }else if(upStu1.getAge()==upStu2.getAge()){
   result=0;
  }else{
   result=-1;
  }
  
  return result;
 }
 
}

一个集合内放入的元素类型类:

定义//定义一个对象
class Student {
 private String name;
 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;
 }
 private int age;
 Student(String name,int age){
  this.name=name;
  this.age=age;
 }
 
}

测试主类:

public class TreeSetDemo{

 public static void main(String[] args) {
  
  Student s1=new Student("zhangsan",24);
  Student s2=new Student("li",23);
 
  MyCompare mc=new MyCompare();
  TreeSet tSet = new TreeSet(mc);
  tSet.add(s1);
  tSet.add(s2);
  Iterator it=tSet.iterator();
  System.out.println("集合中的所有元素为:"+tSet.size());
  while (it.hasNext()) {
   //UpdateStu stu=(UpdateStu)it.next();
   //System.out.println("学号:"+stu.id+";姓名:"+stu.name);
   Student s11=(Student)it.next();
   System.out.println(s11.getName()+","+s11.getAge());
  }

 }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值