基于对象字段对数组列表进行排序

2022-08-31 11:48:00

可能的重复项:
对联系人列表进行排序

我正在将对象存储在 .该类有一个名为 的整数字段。我想从 nodeList 中检索对象,顺序为 。我该怎么做。DataNodeArrayListDataNodedegreeDataNodedegree

List<DataNode> nodeList = new ArrayList<DataNode>();

答案 1

使用自定义比较器:

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;
     }
});

答案 2

修改 DataNode 类,使其实现可比较接口。

public int compareTo(DataNode o)
{
     return(degree - o.degree);
}

然后只需使用

Collections.sort(nodeList);

推荐