2011-02-25 37 views
3

如何排序我的自定義對象的矢量並選擇要排序的屬性?對自定義對象的矢量排序

我確實看到這個問題&答案,但我不太清楚它的基礎上排序它。代碼示例將優先於「方法學」。

Sort a Vector of custom objects

public class ItemLocation { 
    String icon; 
    String title; 
    String message; 
    String subtext; 
    String deviceId; 
    double latCoords; 
    double lngCoords; 
    int expiary; 
    int id; 
    double proximity; 
    String locSeen; 
} 
+3

順便說一句,除非你有很好的理由,否則不應該使用'java.util.Vector'。這個類的日期是Java1.1,並且幾乎被'java.util.Arraylist'代替了。 – OscarRyz 2011-02-25 03:18:51

+0

我不知道這個......謝謝! – 2011-02-25 04:37:38

+0

使用像這樣的嵌套if語句不是一個非常好的OO解決方案。你也不能僅僅調用原始數據類型的「compareTo」,所以代碼變得更加複雜。 – camickr 2011-02-25 04:52:49

回答

14

下面是一個例子,可以讓你通過ItemLocation的指定字段進行排序:

public void sort(final String field, List<ItemLocation> itemLocationList) { 
    Collections.sort(itemLocationList, new Comparator<ItemLocation>() { 
     @Override 
     public int compare(ItemLocation o1, ItemLocation o2) { 
      if(field.equals("icon")) { 
       return o1.icon.compareTo(o2.icon); 
      } if(field.equals("title")) { 
       return o1.title.compareTo(o2.title); 
      } else if(field.equals("message")) { 
       return o1.message.compareTo(o2.message); 
      } 
      . 
      . fill in the rest of the fields... 
      . 
      else if(field.equals("locSeen")) { 
       return o1.locSeen.compareTo(o2.locSeen); 
      } 
     }   
    }); 
} 
+0

Thanks Kurt :)這樣我可以輕鬆地排序我的自定義對象的矢量中的任何字段。 – 2011-02-25 03:49:56

+0

奇妙的庫爾特!在稍作調整以支持原始雙重類型之後,我在幾分鐘之內就完成了這項工作。 (o1.proximity o2.proximity)?1:0; – 2011-02-25 04:46:55

5

參考JavaDoc java.util.Comparablejava.util.Comparator

實現Comparable的類可以與該類的其他實例進行比較。這對於實現自然搜索順序很有用。要允許除班級的自然順序以外的順序,您需要實施Comparator。 A Comparator是一個獨立的對象,可以使用任何標準比較兩個其他對象。

對於您的情況,您可能希望爲要定購的每個不同屬性或可以配置的屬性實施Comparator

ComparableComparator都使用相同的想法來確定排序:方法返回小於0,0或大於0來通知調用方首先排序2個對象中的哪一個。在Comparable的情況下,第一個對象是this

+0

「代碼示例將優於方法學」 - 換句話說,他希望你爲他做到這一點。 Pfft .. – mre 2011-02-25 02:41:38

+0

只是說這是一個新的概念,更多的概念並沒有幫助。要學習的具體代碼是一個更有效的學習工具。 – 2011-02-25 03:42:56

5

這一個工程:

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.List; 

/** 
* ComparableDemo 
* @author Michael 
* @since 2/24/11 
*/ 
public class ComparableDemo 
{ 
    public static void main(String[] args) 
    { 
     List<ItemLocation> itemLocations = new ArrayList<ItemLocation>(); 
     for (String arg : args) 
     { 
      itemLocations.add(new ItemLocation(arg)); 
     } 

     System.out.println("before sort: " + itemLocations); 
     Comparator<ItemLocation> comparator = new ItemLocationComparator(); 
     Collections.sort(itemLocations, comparator); 
     System.out.println("after sort: " + itemLocations); 
    } 
} 

class ItemLocation 
{ 
    String icon; 
    String title; 
    String message; 
    String subtext; 
    String deviceId; 
    double latCoords; 
    double lngCoords; 
    int expiary; 
    int id; 
    double proximity; 
    String locSeen; 

    ItemLocation(String message) 
    { 
     this("", "", message, "", "", 0.0, 0.0, 0, 0, 0.0, ""); 
    } 

    ItemLocation(String icon, String title, String message, String subtext, String deviceId, double latCoords, double lngCoords, int expiary, int id, double proximity, String locSeen) 
    { 
     this.icon = icon; 
     this.title = title; 
     this.message = message; 
     this.subtext = subtext; 
     this.deviceId = deviceId; 
     this.latCoords = latCoords; 
     this.lngCoords = lngCoords; 
     this.expiary = expiary; 
     this.id = id; 
     this.proximity = proximity; 
     this.locSeen = locSeen; 
    } 

    @Override 
    public String toString() 
    { 
     final StringBuilder sb = new StringBuilder(); 
     sb.append("ItemLocation"); 
     sb.append("{message='").append(message).append('\''); 
     sb.append('}'); 
     return sb.toString(); 
    } 
} 



class ItemLocationComparator implements Comparator<ItemLocation> 
{ 
    public int compare(ItemLocation o1, ItemLocation o2) 
    { 
     return o1.message.compareTo(o2.message); 
    } 
} 

這裏的輸出:

C:\JDKs\jdk1.6.0_21\bin\java -Didea.launcher.port=7534 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 10.0.2\bin" -Dfile.encoding=windows-1252 com.intellij.rt.execution.application.AppMain ComparableDemo zeb meme apple 
before sort: [ItemLocation{message='zeb'}, ItemLocation{message='meme'}, ItemLocation{message='apple'}] 
after sort: [ItemLocation{message='apple'}, ItemLocation{message='meme'}, ItemLocation{message='zeb'}] 

Process finished with exit code 0 
3

假設我們有一個int類型和一個字符串的類。我可以定義該類的一個對象如何與其他對象進行比較。

我可以選擇任何標準。例如,我可能決定根據int進行排序。如果我碰巧有兩個int的具有相同的價值,我可以決定的字符串作爲附加條件,這樣的事情:

// this class *knows* how to "compare" against him self 
class CustomObject implements Comparable<CustomObject> { 
    String aString; 
    int aInt; 
    ... 
    public int compareTo(CustomObject two) { 
     int diff = this.aInt - two.aInt;//<-- compare ints 
     if(diff != 0) { // they have different int 
      return diff; 
     }  
     return this.aString.compareTo(two.aString);//<-- compare strings... 
    } 
    ... 
} 

這裏有一個完整的運行演示...

import java.util.*; 
class SortDemo { 
    public static void main(String ... args) { 
     // create a bunch and sort them 
     List<CustomObject> list = Arrays.asList(
      new CustomObject(3, "Blah"), 
      new CustomObject(30, "Bar"), 
      new CustomObject(1, "Zzz"), 
      new CustomObject(1, "Aaa") 
     ); 
     System.out.println("before: "+ list); 
     Collections.sort(list); 
     System.out.println("after : "+ list); 
    } 
} 
// this class *knows* how to "compare" against him self 
class CustomObject implements Comparable<CustomObject> { 
    String aString; 
    int aInt; 
    CustomObject(int i, String s) { 
     aInt = i; 
     aString = s; 
    } 
    // comparable interface lets you 
    // specify "HOW" to compare two 
    // custom objects 
    public int compareTo(CustomObject two) { 
     // I migth compare them using the int first 
     // and if they're the same, use the string... 
     int diff = this.aInt - two.aInt; 
     if(diff != 0) { // they have different int 
      return diff; 
     } 

     // else let the strings compare them selves 
     return this.aString.compareTo(two.aString); 
    } 
    public String toString(){ 
     return "CustomObject[aInt="+aInt+", aString="+aString+"]"; 
    } 
} 

這裏的輸出:

before: [CustomObject[aInt=3, aString=Blah], CustomObject[aInt=30, aString=Bar], CustomObject[aInt=1, aString=Zzz], CustomObject[aInt=1, aString=Aaa]] 
after : [CustomObject[aInt=1, aString=Aaa], CustomObject[aInt=1, aString=Zzz], CustomObject[aInt=3, aString=Blah], CustomObject[aInt=30, aString=Bar]] 

我希望這足夠

清楚您也可以通過一個定製協mparator。讓我知道你是否需要一個樣本。