本帖最后由 long362144768 于 2013-9-30 17:46 编辑
我发现你的类很混乱,看不懂你的SetDemo做什么用呢,我这里有个类似代码,你看看说不定能对你有用
- <P>import java.util.Comparator;
- import java.util.TreeSet;</P>
- <P>import java.util.Set;
- /**
- *第十题:声明类Student,包含3个成员变量:name、age、score,
- *创建5个对象装入TreeSet,按照成绩排序输出结果(考虑成绩相同的问题)
- * @author chenlong
- */
- public class Test10 {
- public static void main(String[] args) {
- Set<student> treeSet = new TreeSet<student>(
- //定义匿名内部类进行定制降序排序,实现comparator接口
- new Comparator<Object>(){
- public int compare(Object o1, Object o2){
- student s1 = (student) o1;
- student s2 = (student) o2;</P>
- <P> //保证是降序排列,如果是return s1.score >= s2.score? 1:-1;则为升序排列
- return s1.score >= s2.score? -1:1;
- }
- }
- );
- treeSet.add(new student("张三", 23, 76));
- treeSet.add(new student("李四", 24, 84));
- treeSet.add(new student("王五", 22, 91));
- treeSet.add(new student("赵六", 23, 87));
- treeSet.add(new student("钱七", 24, 84));
- System.out.println(treeSet);
- }
- }
- class student implements Comparable<Object>{//实现comparable借口
- String name;
- int age;
- double score;
- public student(String name, int age, double score) {
- this.name = name;
- this.age = age;
- this.score = score;
- }
-
- public String toString(){
- return "student对象:"+this.name+" 年龄"+this.age+" 成绩"+this.score;
-
- }
-
- //主要用于消除相同元素,姓名和年龄相同则视为同一对象
- @Override
- public int compareTo(Object o) {
- student stu = (student) o;
- int num = this.name.compareTo(stu.name);
- return 0 == num?new Integer(this.age).compareTo(new Integer(stu.age)):num;
- }
-
- }
- </P>
复制代码 |