這篇文章將為大家詳細(xì)講解有關(guān)如何使用TreeSet集合,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
需求:鍵盤錄入5個學(xué)生信息(姓名,語文成績,數(shù)學(xué)成績,英語成績),按照總分從高到低輸出到控制臺。分析:1、創(chuàng)建鍵盤錄入對象;
2、創(chuàng)建TreeSet集合,使用匿名內(nèi)部類實現(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é)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
文章題目:如何使用TreeSet集合-創(chuàng)新互聯(lián)
網(wǎng)站URL:http://chinadenli.net/article12/dejgdc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動態(tài)網(wǎng)站、營銷型網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計、網(wǎng)站維護(hù)、企業(yè)網(wǎng)站制作、網(wǎng)站營銷
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容