摘要:Treeset為自然排序0-9,a-z,新增一個person物件,用iterator取出集合
package com.cht.commons.persistence.query;
import java.util.Iterator;
import java.util.TreeSet;
public class testCollection {
public static void main(String[] args) {
System.out.println("=================TreeSet會自動排序1-9,a-Z");
TreeSet ts=new TreeSet();
ts.add(new People(5,"zhang"));
ts.add(new People(3,"wang"));
ts.add(new People(4,"li"));
//TreeSet会按自然排序法自动排序,即3在5前,a在b前,如果传入的是自定义的对象,必须让该对象实现 Comparable接口
Iterator its=ts.iterator();
//TreeSet同样没有取出元素的方法,只能用迭代器
while(its.hasNext()){
System.out.println(its.next());
}
}
}
class People implements Comparable{
int id;
String name;
People(int id,String name){
this.id=id;
this.name=name;
}
public String toString(){
return "id:"+id+" name:"+name;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
People p=(People)o;
return id>p.id ? 1:(id<p.id?-1:0);
//重写compareTo方法,如果id有重复,可以对比完id后再对比name,使用String的compareTo方法
}
}
ref:http://www.pocketdigi.com/20110804/435.html