溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用TreeSet集合

發(fā)布時間:2021-11-26 09:56:53 來源:億速云 閱讀:128 作者:柒染 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)如何使用TreeSet集合,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

需求:鍵盤錄入5個學(xué)生信息(姓名,語文成績,數(shù)學(xué)成績,英語成績),按照總分從高到低輸出到控制臺。分析:1、創(chuàng)建鍵盤錄入對象;
          2、創(chuàng)建TreeSet集合,使用匿名內(nèi)部類實(shí)現(xiàn)Comparator接口,重寫compara方法
          3、判斷集合中元素的個數(shù),向其中添加元素
          4、遍歷集合

class Demo_TreeSet{
         public static void main(String[] args){
                Scanner sc = new Scanner(System.in);
                System.out.println("請輸入學(xué)生成績格式,語文成績,數(shù)學(xué)成績,英語成績,總成績");
                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;
        }
}

關(guān)于如何使用TreeSet集合就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI