本帖最后由 wenweishan2015 于 2015-6-4 22:59 编辑
我写的这个程序,我TreeSet里装入了5个对象,为什么最后排序出来的结果不是5个?(几个的都有)代码如下:
/**
* 声明类Student,包含3个成员变量:name、age、score,创建5个对象装入TreeSet,按照成绩排序输出结果。
* */
public class Test10 {
private TreeSet<Student> stus;
public Test10(){
//初始化TreeSet对象
stus = new TreeSet<Student>();
//添加5个Student对象
for(int i = 0;i < 5;i++){
Student stu = new Student("name"+i, (int)(Math.random()*10+10), (int)(Math.random()*10+100));
this.stus.add(stu);
}
}
public TreeSet<Student> getStus() {
return this.stus;
}
public void setStus(TreeSet<Student> stus) {
this.stus = stus;
}
public static void main(String[] args) {
//创建test对象
Test10 test = new Test10();
//遍历排序好的TreeSet
Iterator<Student> it = test.getStus().iterator();
while(it.hasNext()){
Student s = it.next();
System.out.println(s.getName()+":"+s.getScore());
}
}
//声明Student类
class Student implements Comparable<Student>{
//私有成员变量
private String name;
private int age;
private int score;
//无参构造函数
public Student(){}
//带参数的构造函数
public Student(String name,int age,int score){
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
//实现comparable接口进行排序
@Override
public int compareTo(Student s) {
if (s instanceof Student)
{
Student stu = (Student)s;
if (this.score > stu.getScore())
{
return 1;
}
else if (this.score == stu.getScore())
{
return 0;
}
else
{
return -1;
}
}
return 0;
}
}
}
[/code] |
|