編程思路是:實現一個類對ArrayList進行包裝,當程序試圖向ArrayList中放入數據時,程序將先檢查該元素與ArrayList集合中其他元素的大小,然后將該元素插入到指定位置。
class MyBean implements Comparable{
public int compareTo(Object obj){
if(! obj instanceof MyBean)
throw new ClassCastException()。
MyBean other = (MyBean) obj;
return age > other.age?1:age== other.age?0:-1;
}
}
class MyTreeSet {
private ArrayList datas = new ArrayList();
public void add(Object obj){
for(int i=0;i<datas.size();i++){
if(obj.compareTo(datas.get(i) != 1){
datas.add(i,obj);
}
}
}
}