package com.itheima;
import java.util.Iterator;
import java.util.TreeSet;
/*
题目:声明类Student,包含3个成员变量:name、age、score,创建5个对象装入TreeSet,按照成绩排序输出结果(考虑成绩相同的问题)。
分析:
1.声明类Student,实现Comparable接口,并定义三个成员变量name、age、score
2.复写compareTo(){}
3.判断是否是学生这个类。
4.按照成绩对学生进行排序
5.使用TreeSet ts=new TreeSet();ts.add(new Student("xxx",20,87.8));创建五个对象,并将对象装入TreeSet容器。
6.在控制台打印出来。
步骤:
1.class Student implements Comparable{}
2.public int compareTo(Object obj){}
3.if (!(obj instanceof Student))
4.if (this.score > s.score)
return 1;
if (this.score == s.score)
return 0;
return -1;
5.TreeSet ts=new TreeSet();
ts.add(new Student("xxx",20,87.8));(五个)
6.使用迭代器进行输出,并考虑成绩重复的情况。
*/
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.score > s.score)
return 1;
if (this.score == s.score)
return 0;
return -1;
}
//构造函数,用来初始化变量
Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() { //name属性的get方法
return name;
}
public int getAge() { //age属性的get方法
return age;
}
public double getscore() { //score属性的get方法
return score;
}
}
public class Test10 {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet ts=new TreeSet();
ts.add(new Student("xxx",20,87.8)); //往容器中添加5个对象
ts.add(new Student("yyy",21,100));
ts.add(new Student("zzz",18,60));
ts.add(new Student("aaa",22,92.7));
ts.add(new Student("bbb",14,92.7));
Iterator it=ts.iterator();
while(it.hasNext())
{
Student stu=(Student)it.next(); //将其强制转换成Student类型。
System.out.println("姓名: "+stu.getName()+" 年龄: "+stu.getAge()+" 成绩: "+stu.getscore());
}
}
}
- 1
- 2
- 3
前往页