今天很累,但博客还得要写
一个小例子,把add到TreeSet中的元素,按年龄大小排序,如果年龄相同,按姓名排列
package cn.tsp2c.liubao;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class TestTreeSet {
public static void main(String[] args){
Set set=new TreeSet();
set.add(new Dog("hau",3));
set.add(new Dog("tom",5));
set.add(new Dog("jerry",1));
set.add(new Dog("yao",8));
set.add(new Dog("tmac",7));
set.add(new Dog("kobe",7));
set.add(new Dog("iverson",7));
set.add(new Dog("bryant",7));
set.add(new Dog("bbcsdt",7));
for(Iterator it=set.iterator();it.hasNext();){
System.out.println(it.next());
}
}
}
class Dog implements Comparable{
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
//这里是偶今天所学的东东,成就感谈不上,不过还蛮高兴的!!!
public int compareTo(Object o) {
Dog d=(Dog)o;
if(this.age!=d.age)
return this.age-d.age;
else{
return this.name.compareTo(d.name);
}
}
@Override
public String toString() {
return "Dog{" + "name=" + name + "\tage=" + age + '}';
}
}
总结:在实现过程中一定要注意所在类一定要有implements Comparable的关键字,分布实现比较,首先实现按年龄的比较,然后再去实现按姓名的排序,两步完成后,偶的小程序也就ok了,呵呵~~类但快乐着~~~