日期:2014-05-20 浏览次数:21151 次
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;
}
}