温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用TreeSet集合

发布时间:2021-11-26 09:56:53 来源:亿速云 阅读:114 作者:柒染 栏目:编程语言

这篇文章将为大家详细讲解有关如何使用TreeSet集合,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

需求:键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低输出到控制台。分析:1、创建键盘录入对象;
          2、创建TreeSet集合,使用匿名内部类实现Comparator接口,重写compara方法
          3、判断集合中元素的个数,向其中添加元素
          4、遍历集合

class Demo_TreeSet{
         public static void main(String[] args){
                Scanner sc = new Scanner(System.in);
                System.out.println("请输入学生成绩格式,语文成绩,数学成绩,英语成绩,总成绩");
                TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>{
                       public int compara( Student s1,Student s2);
                                  int num = s2.getSum() - s1.getSum();
                                  return num == 0 ? 1 : num;
                });
               while(ts.size()<5){
                    String line = sc.nextLine();                                       
                    String[] arr = line.Split(",");
                    int chinese = Integer.paserInt(arr[1]);
                    int math = Integer.paserInt(arr[2]);
                    int  english = Integer.paserInt(arr[3]);
                    ts.add(new Student(arr[0],chinese,math,english));
                }
                for(Student : s : ts){
                      System.out.println(s);
                 }
          }
}
class Student{
    private String name;
    private int chinses;
    private int math;
    private int enlish;

    public Student() {}
    public Student(String name, int chinese, int math, int english) {
                super();
                this.name = name;
                this.chinese = chinese;
                this.math = math;
                this.english = english;
                this.sum = this.chinese + this.math + this.english;
        }
        public int getSum() {
                return sum;
        }
        
        public String toString() {
                return name + "," + chinese + "," + math + "," + english + "," + sum;
        }
}

关于如何使用TreeSet集合就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI