伙计们,我的方法需要在已排序的列表中添加一个新元素,即在适当的位置。关键是该方法检查最低行索引,然后比较其cols。例如,
board.set(2,2, 11);
board.set(-1,0,22);
board.set(-1,2,33);
board.set(1,0,44);
board.set(3,0,55);
board.set(3,1,66);
board.set(3,3,77);
board.set(3,2,88);
board.set(-1,1,99);
结果应为:
[(-1,0,22), (-1,1,99), (-1,2,33), (1,0,44), (2,2,11), (3,0,55), (3,1,66), (3,2,88), (3,3,77)]
但我的程序会打印出来:
[(-1,0,22), (-1,1,99), (3,2,88), (3,3,77), (3,1,66), (3,0,55), (1,0,44), (-1,2,33), (2,2,11)]
即。它不会将物体放入适当的位置。
我有一个LinkedList<RowColElem<T>>rowColSeq
,其中添加了对象并在“随时随地”放置到适当的位置。我的代码丢失了什么?
注意:我不允许使用比较器,类似的界面!
LinkedList<RowColElem<T>> rowColSeq; // Is not empty, already contains objects!
private void sortedRowColSeq(int row, int col, T x){
RowColElem<T> object = new RowColElem<T>(row, col, x);
ListIterator<RowColElem<T>> iter = rowColSeq.listIterator();
RowColElem<T> inListObject;
boolean added = false;
while(iter.hasNext()){
inListObject = iter.next();
if(object.getRow() < inListObject.getRow()){
iter.previous();
iter.add(object);
undoStack.push(object);
added = true;
break;
}
else if(object.getRow() == inListObject.getRow()){
if(object.getCol() < inListObject.getCol()){
iter.previous();
iter.add(object);
undoStack.push(object);
added = true;
}
}
else{
iter.add(object);
undoStack.push(object);
added = true;
break;
}
}
}
答案 0 :(得分:1)
如果新元素大于某些元素,则可能无法添加。您必须在更大或最后一个之前输入。
boolean added = false;
while(iter.hasNext()){
inListObject = iter.next();
if(object.getRow() < inListObject.getRow() ||
object.getRow() == inListObject.getRow()) &&
object.getCol() < inListObject.getCol() ){
if( iter.hasPrevious() ){
iter.previous();
iter.add(object);
} else {
rowColSeq.addFirst( object );
}
undoStack.push(object);
added = true;
break;
}
}
if( ! added ){
rowColSeq.addLast(object);
undoStack.push(object);
added = true;
}
使用iter.previous()的方法在某些情况下注定要失败,所以我添加了测试和替代代码。