gpt4 book ai didi

java - 使用迭代器对列表进行排序

转载 作者:行者123 更新时间:2023-12-01 22:04:18 25 4
gpt4 key购买 nike

我需要先按行号,然后按列号对对象列表进行排序。每当用户 set(row, col, x) ,放入rowColSeq在某个位置上。例如,

board.set(1, 1, "aa");
board.set(1, 3, "aa");
board.set(0, 1, "B");
board.set(0, 2, "B");
board.set(1, 0, "aa");

列表应按以下方式排序:

[0,1,"B"], [0,2,"B"], [1,0,"aa"], [1,1,"aa"], [1,3,"aa"] 

但是我的代码给了我无限循环。 smb 可以告诉我我用我的代码做了什么吗?

假设列表不为空!

  LinkedList<RowColElem<T>> rowColElems; //contains some info

private void sortedRowColSeq(int row, int col, T x){
RowColElem<T> object = new RowColElem<T>(row, col, x);
ListIterator<RowColElem<T>> iter = rowColSeq.listIterator();
while(iter.hasNext()){
RowColElem<T> inListObject = iter.next();
if(object.getRow() < inListObject.getRow()){
iter.previous();
iter.add(object);
}
else if(object.getRow() == inListObject.getRow()){
if(object.getCol() < inListObject.getCol()){
iter.previous();
iter.add(object);
}
else{
iter.add(object);
}
}
else{
iter.add(object);
}
}
}

<强> RowColElem<T>

public class RowColElem<T>{
private int row;
private int col;
private T elem;

// Create a RowColElem with the parameter parts
public RowColElem(int r, int c, T e){
this.row = r;
this.col = c;
this.elem = e;
}

// Return the row
public int getRow(){
return this.row;
}

// Return the column
public int getCol(){
return this.col;
}

// Return the element
public T getElem(){
return this.elem;
}

// Return a pretty string version of the triple formated as
// (row,col,elem)
public String toString(){
return String.format("(%d,%d,%s)",row,col,elem);
}

@SuppressWarnings("unchecked")
// Perform a deep equality check between this RowColElem and another
// object
public boolean equals(Object other){
if(other == null || !(other instanceof RowColElem)){
return false;
}
RowColElem<T> that = (RowColElem<T>) other;
return
this.row == that.row &&
this.col == that.col &&
this.elem.equals(that.elem);
}
}

最佳答案

您的基本问题是您编写了排序代码。解决方案是单行:

Collections.sort(Comparators.comparing(RowColElem::getRow)
.andThen(RowColElem::getCol));

关于java - 使用迭代器对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33058769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com