※ 引述《tsya (tsya)》之銘言:
: public int compareTo(Element other){
: return this.value-other.value;
: }
就把這個改成 compare 兩個 object 的 name 就行啊...
參考 API 的 String.compareTo()....
: 在main method裡面做排序
: import java.util.*;
: class Sort{
: public static void main(String[] args){
: Element[] e=new Element[5];
: e[0]=new Element(1,"Apple");
: e[1]=new Element(2,"Azure");
: e[2]=new Element(5,"Apply");
: e[3]=new Element(3,"Adapt");
: e[4]=new Element(4,"Adept");
: System.out.println(Arrays.toString(e));
: Arrays.sort(e);
: System.out.println(Arrays.toString(e));
: }
: }
: 排序value 的部分非常成功
: [value = 1, value = 2, value = 5, value = 3, value = 4]
: [value = 1, value = 2, value = 3, value = 4, value = 5]
: 但是排序name就不知道怎麼寫了
: 我參考這個網頁
: http://www.rgagnon.com/javadetails/java-0343.html
: 但是他只有教排序String Array
: 請問含有String的Object Array應如何排序?
: 請給我一些觀念可以嗎?
: 謝謝
其實如果是這種 object 要排序,而且不是每次都是根據同樣的 member 排序的話
會比較建議做幾個 Comparator, 那麼在不同的時候無論是 sort by index 或是
sort by name, sort by size 都可以做到,只要換一個 Comparator 就可以了。
請參考 Arrays.sort(Object[] a, Comparator c) 函數
--
很多人以為 所以我要 其實我是個快
我是大學生 告訴大家 三十歲的怪叔叔
● ●/ ︿ ︿
/勁\ <勁 ●
ㄨ /\ ㄨ
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 147.8.130.225
※ 編輯: superlubu 來自: 147.8.130.225 (05/19 12:09)
※ 編輯: superlubu 來自: 147.8.130.225 (05/19 12:09)