【发布时间】:2018-05-05 08:22:04
【问题描述】:
我正在尝试将整数值插入到列表中。插入值后,我将检查当前值和下一个值之间是否相差 10。如果是,我将在第一个值上加 10并将其添加回列表。
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(20);
arrayList.add(40);
arrayList.add(50);
arrayList.add(70);
arrayList.add(90);
ListIterator<Integer> iterator = arrayList.listIterator();
int firstVal = 0;
int secVal = 0;
while (iterator.hasNext()) {
if (iterator.hasPrevious()) {
firstVal = iterator.previous();
iterator.next();
}
secVal = iterator.next();
System.out.println("FirstValue " + firstVal);
System.out.println("secVal " + secVal);
if (firstVal != 0) {
if ((secVal - firstVal) > 10) {
//iterator.previousIndex();
iterator.add(firstVal + 10);
firstVal = 0;
iterator.next();
}
}
}
System.out.println("iterator " + iterator.toString());
}
有两件事我无法使其正常工作。
首先,当我尝试将差异值添加回列表时,它没有添加到正确的索引中。例如,第一个值为 20,第二个值为 40,新值 30 在 40 之后添加.
其次,这里没有创建 70 和 90 之间的缺失值,即 80。
请纠正我在这里遗漏的逻辑。
感谢您的宝贵时间。
【问题讨论】:
-
您希望
previousIndex()做什么?阅读该方法的 Javadoc,看看它是否符合您的预期。 -
@tgdavies 实际上它对我的情况没有任何作用,现在就发表了评论。感谢您的突出显示。
-
您不应将其注释掉。您需要致电
previous() -
@tgdavies 非常感谢。您强调了问题所在。
-
@user7 在我的实际代码中修改为 previous() ..谢谢
标签: java arraylist listiterator