我编写的应用TreeSet进行排序的代码
自己写的练习,但是不知道为什么没有任何结果,并且没有报错啊!
MyTreeSet类
package com.work;import java.util.Iterator;import java.util.TreeSet;public class MyTreeSet { /** * @param args */ static TreeSet<Res> tree=new TreeSet<Res>(); MyTreeSet a=new MyTreeSet(); public static void main(String[] args) { // TODO Auto-generated method stub tree.add(new Res("a", 21)); tree.add(new Res("b", 19)); tree.add(new Res("c", 32)); tree.add(new Res("d", 8)); } public void get(){ Iterator<Res> a=tree.iterator(); while (a.hasNext()) { Res res = (Res) a.next(); System.out.println(res.getName()+"-----------"+res.getAge()); } }}package com.work;class Res implements Comparable<Res> { String name; int age; public Res(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public int compareTo(Res o) { // TODO Auto-generated method stub if (!(o instanceof Res)) { throw new RuntimeException(); } if (this.age == o.age) { return this.name.compareTo(o.name); } else if (this.age - o.age < 0) { return -1; } return 1; } }
}
}
}
[解决办法]
MyTreeSet a=new MyTreeSet();应该放到main()中,另外get()方法没有调用,调用后就有结果了。