4.25学习内容

TreeSet集合比较器Comparator排序的使用

1.为保证唯一性需要重新定义比较器,添加主要判断条件以及次要判断条件。

2.通过加强for循环来遍历集合中的数据。

实践了黑马程序员中P248:成绩排序  的案例

Student类
******************
public class Student {
    private int Chinese;
    private int Math;

    private String Name ;

    public Student() {
    }

    public Student(String Name, int Chinese, int Math) {
        this.Name = Name;
        this.Math = Math;
        this.Chinese = Chinese;
    }

    public int getChinese() {
        return Chinese;
    }

    public void setChinese(int chinese) {
        this.Chinese = chinese;
    }

    public int getMath() {
        return Math;
    }

    public void setMath(int math) {
        this.Math = math;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        this.Name = name;
    }
    public int getnum() {
        return this.Chinese + this.Math;
    }
}
TreeSetDemo
*******************************
import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetDemo {
    public static void main(String[] args) {
//        重新定义比较器
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int num = s1.getnum() - s2.getnum();
                int num1 = num == 0 ? s1.getName().compareTo(s2.getName()):num;
                return num1;
            }
        });
//        创造对象
        Student s1 = new Student("a",90,98);
        Student s2 = new Student("b",90,98);
        Student s3 = new Student("c",95,98);
        Student s4 = new Student("d",94,96);
        Student s5 = new Student("e",99,99);
        Student s6 = new Student("f",99,100);
//        添加独对象
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);
//       遍历
        for(Student g : ts){
            System.out.println("姓名:"+g.getName() + ","+"数学成绩:"+g.getMath()+",语文成绩:"+g.getChinese());
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值