可能的复制品: 对联系人的数组列表进行排序
我将 DataNode对象存储在一个 ArrayList中。 DataNode类有一个名为 degree的整数字段。 我想从 nodeList 中以 degree的递增顺序检索 DataNode对象。我如何做到这一点。
DataNode
ArrayList
degree
List<DataNode> nodeList = new ArrayList<DataNode>();
Use a custom comparator:
Collections.sort(nodeList, new Comparator<DataNode>(){ public int compare(DataNode o1, DataNode o2){ if(o1.degree == o2.degree) return 0; return o1.degree < o2.degree ? -1 : 1; } });
You can use the Bean Comparator to sort on any property in your custom class.
Modify the DataNode class so that it implements Comparable interface.
public int compareTo(DataNode o) { return(degree - o.degree); }
then just use
Collections.sort(nodeList);