排序"链接"在java中的列表

时间:2018-05-25 23:37:30

标签: java sorting

我在java中有以下实体:

public class TodoEntity {
   private int id;
  private int previousId;
}

//Array to sort
List<TodoEntity> unsorted=new ArrayList<>();

对这个数组进行排序的最快方法是什么,以便每个previousId匹配id(分别是之前/之后的项目)

当前实施

 public static List<TodoEntity> sortEntites(LinkedList<TodoEntity> todoEntities) {
    boolean isClean=true;
    while(isClean){
        boolean isRoundUnclean=false;
        for(int i=0;i<todoEntities.size();i++){
            TodoEntity todoEntity=todoEntities.get(i);
            if(i>0){
                TodoEntity todoEntityPrevious=todoEntities.get(i-1);
                if(todoEntity.getPrevious()!= null && !todoEntity.getPrevious().equals(todoEntityPrevious.getGuid())){
                    int index=getIndex(todoEntities,todoEntity.getPrevious());
                    todoEntities.remove(i);
                    todoEntities.add(index,todoEntity);
                    isRoundUnclean=true;
                    break;
                }
                if(todoEntity.getPrevious()==null){
                    todoEntities.remove(i);
                    todoEntities.add(0,todoEntity);
                }
            }
        }
        isClean = isRoundUnclean;
    }
    return todoEntities;
}

1 个答案:

答案 0 :(得分:0)

此列表未链接。链表是存储引用和数据而不是数组数据的列表。要创建链接列表,只需更改

  

List<TodoEntity> unsorted=new ArrayList<>();

List<TodoEntity> unsorted = new LinkedList<>();

但是,要回答您的问题,只需致电Collections.sort(unsorted);对您的列表进行排序,并添加与您的TodoEntity类相似的内容。

示例(按匹配ID匹配的升序对ID进行排序):

public class TodoEntity implements Comparable<TodoEntity>{
    private int id;
    private int previousId;
    @Override
    public int compareTo(TodoEntity other){
        if(this.id == other.previousID)
            return -1;
        if(this.previousID == other.id)
            return 1;
        return 0;
    }
}