“黑馬程序員”聲明類Student,包含3個成員變量:name、age、score,創建5個對象裝入TreeSet,按照成績排序輸出結果(考慮成績相同的問題)

 ------- <a href="http://www.itheima.com" target="blank">android培訓</a>、<a href="http://www.itheima.com" target="blank">java培訓</a>、期待與您交流! ----------

package test;

import java.util.*;
public class ten {
public static void main(String[] args) {
TreeSet ts=new TreeSet();
ts.add(new Student("張三",23,78.9));
ts.add(new Student("李四",45,90.99));
ts.add(new Student("王五",45,90));
ts.add(new Student("趙六",34,89));
ts.add(new Student("小明",14,89.7));
Iterator it=ts.iterator();
   while(it.hasNext())
   {
    Student stu=(Student)it.next();
    System.out.println(stu.getName()+"...."+stu.getAge()+"....."+stu.getscore());
//System.out.println(it.next());
   }
}


}
class Student implements Comparable
{
private String name;
private int age;
private double score;
public int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("不是學生類型");
Student s=(Student)obj;
if(this.age>s.age)
return 1;
if(this.age==s.age)
return 0;
return -1;
}
Student(String name,int age,double score)
{
this.name=name;
this.age=age;
this.score=score;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public double getscore()
{
return score;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章