------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
黑马基础测试题 第十题
package com.itheima;
/**
* 第十题
*
* 声明类Student,包含3个成员变量:name、age、score,创建5个对象装入TreeSet,按照成绩排序输出结果(考虑成绩相同的问题).
*
* 分析:
* 1.创建TreeSet集合
* 2.创建五个student对象并加入set集合
* 3.定义方法,迭代set集合,并取出迭代器中的元素
* 4.创建Student类,继承Comparable,实现compareto()方法
*
*/
import java.util.Iterator;
import java.util.TreeSet;
public class Test10 {
public static void main(String[] args) {
// 创建TreeSet集合 泛型为Student
TreeSet<Student_2> set = new TreeSet<Student_2>();
// 创建五个student并加入set集合
set.add(new Student_2("孙悟空", 500, 90));
set.add(new Student_2("猪八戒", 350, 80));
set.add(new Student_2("沙悟净", 300, 85));
set.add(new Student_2("小白龙", 200, 85));
set.add(new Student_2("唐三藏", 30, 95));
// 调用所定义的对set集合的输出方法
Myout(set);
}
public static void Myout(TreeSet<Student_2> set) {
// 迭代set集合
Iterator<Student_2> it = set.iterator();
// 取出迭代器中的元素
while (it.hasNext()) {
Student_2 stu = (Student_2) it.next();
System.out.println(stu.toString());
}
}
}
/*
* 定义Student类,并继承Comparable,实现compareto()方法
*/
class Student_2 implements Comparable<Student_2> {
private String name;
private int age;
private double score;
public Student_2() {
}
// 带参数构造器
public Student_2(String name, int age, double score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
// get set 方法
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 double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
// 覆盖compareTo()方法,定义出自己所需的情况
public int compareTo(Student_2 o) {
Student_2 stu = o;
// if判断 先通过成绩进行排序和年龄进行排序
if (this.score < stu.score)
return (int) -1;
else if (this.score > stu.score)
return 1;
else if (this.age > stu.age)
return 1;
else if (this.age < stu.age)
return -1;
else if (this.score == stu.score && this.age == stu.age)
// 分数年龄相同则返回姓名的字典顺序差,通过姓名进行排序
return this.name.compareTo(stu.name);
return 0;
}
// 覆盖toString()方法方便调试和显示
public String toString() {
return "Student [姓名:" + name + ", 年龄:" + age + ", 成绩:" + score+ "]";
}
}