如果使用 ArrayList 來儲存自定義的 Object
例如
1 |
ArrayList<node> al = new ArrayList<node>(); |
(<node> 指的是 ArrayList 存放的物件是 node 型態的物件)
這時想用 Collections.Sort(al) 來排序這個 ArrayList 就會出錯
程式會不知道該怎麼執行排序~
此時就必須實做 Comparator 這個 Interface,教 Collections 要怎麼做排序。
先新增一個 Class,內容像是這樣:
1 2 3 4 5 6 7 8 9 10 |
Class newComparator implements Comparator { public int compare(Object o1,Object o2) { //實做Comparator.compare node n1 = (node)o1; //將引入的物件轉換型別為自定義的物件 node n2 = (node)o2; if (n1.getValue > n2.getValue) return 1 ; else if (n1.getValue < n2.getValue) return - 1 ; else return 0 ; } } |
然後主程式中就可以直接做 Sort,並且引入這個自定義的 Comparator
就可以對自定義的物件們針對特定欄位做排序了。
1 |
Collections.Sort(al, new newComparator); |
沒有留言:
張貼留言