2012-05-23 38 views
3

我想那種有型節點一個ArrayList,像這樣:按字典順序排列ArrayList <Node>?

[[country1: null], [name2: null], [city3: null], [region4: null], [name6: null]] 

爲了得到節點的名字我使用功能getNodeName()我已經尋找到的值,因此

ArrayNode.get(0).getNodeName() // return country1 

collection.sort但我不知道我會怎麼做,謝謝你提前。

+0

怎樣的'Node'類看?通過它的屬性你想排序? –

+0

不是*確切*重複,但幾乎http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property – Corbin

回答

3

使用Comparator對象定義比較邏輯。

類似的東西:

ArrayList<Node> nodes; 
     Collections.sort(nodes, new Comparator<Node>() { 
      @Override 
      public int compare(Node o1, Node o2) { 
       return o1.getNodeName().compareTo(o2.getNodeName()); 
      } 
     }); 
3

我想你想要java.util.Comparator。您可以使用隨Collections.sort

3

創建Comparator的排序按節點名稱,然後Collections.sort(list,comparator)