1. set 有序集合
2. 能够使用set 的类,必须实现 Comparable 接口
3. 示例:
/**
*
*/
package p_java;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class Test implements Comparable<Object> {
private int id;
private String name;
public Test(int id,String name){
this.id=id;
this.name=name;
}
public static void main(String[] args) {
Test t1= new Test(101, "a");
Test t2= new Test(88, "b");
Test t3= new Test(120, "c");
Test t4= new Test(100, "d");
Set<Test> set = new TreeSet<Test>();
set.add(t1);
set.add(t2);
set.add(t3);
set.add(t4);
Iterator<Test> tIterator= set.iterator();
while (tIterator.hasNext()) {
Test resulTest = tIterator.next();
System.out.println(resulTest.id+resulTest.name);
}
}
@Override
public int compareTo(Object o) {
Test test =(Test)o;
int result=0;
result=(id>test.id)?1:((id==test.id)?0:-1);
return result;
}
}
4. 结果
88b
100d
101a
120c