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

class MyBean implements Comparable{  //comparaable是一個進行排序的類, 數組

public int compareTo(Object obj){  //這comparable接口中必須實現的方法 當返回值>0時排前面,=0排中間 <0排後面 spa

if(! obj instanceof MyBean)           對象

throw new ClassCastException() //具體異常的名稱,我要查jdk文檔。 排序

 

MyBean other = (MyBean) obj; 接口

return age > other.age?1:age== other.age?0:-1; 文檔

} get

} io

 

 

class MyTreeSet { ast

private ArrayList  datas = new ArrayList(); class

public void add(Object obj){  //調用方法者存入一個對象

for(int i=0;i<datas.size();i++){   把數組中的全部元素進行迭代

if(obj.compareTo(datas.get(i) != 1){  //跟據上面定義的比較器進行比較兩個對象

datas.add(i,obj);      

}

}

}

}

相關文章
相關標籤/搜索