在学习了一段时间的Java之后,我决定修改listIterator
方法。所以我做了下面的简单代码:
List<String> colors = new ArrayList<>();
colors.add("red");
colors.add("blue");
colors.add("green");
ListIterator<String> iterator = colors.listIterator();
while (iterator.hasNext()){
String color = iterator.next();
System.out.println(color);
if (color.equals("blue")){
iterator.add("yellow");
}
}
我期望的是迭代器'yellow'
在之后添加'blue'
。但是当我运行它时,我感到惊讶。结果是:
red-blue-green
而且不像我预期的那样:
red-blue-yellow-green
当迭代器 add()
不更新迭代过程中的收集时,迭代器的方法有什么意义?是的,如果我要致电,它将为我显示所有4种颜色。但是为什么不简单添加以便Iterator可以“看到”它呢?System.out.println(colors)
'yellow'
首先,就是这样,因为它是这样指定的:
新元素将插入到隐式光标之前:对next的后续调用将不受影响,而对Previous的后续调用将返回新元素。
我想这个决定背后的原理是这样的:如果您只是添加了一个元素,通常不希望在下次调用时立即对其进行处理next()
。相反,大多数情况下,您只想在开始迭代之前根据集合中包含的元素将元素添加到集合中。您已经知道刚刚添加的元素,因此可以直接进行它需要的任何处理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句