ArrayList如何實現插入的數據按自定義的方式有序存放?


編程思路是:實現一個類對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);

}

}

}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM