【发布时间】:2018-03-02 21:03:37
【问题描述】:
我有一个Collection<T>,名为“col”。包含类 T 的内容并不重要。当我迭代集合时,在每次迭代时,我都需要拥有当前元素和下一个元素。
Iterator it = col.iterator();
while (it.hasNext()) {
T line = (T) it.next();
T nextLine = it.hasNext()? NEXT_LINE : null;
// more Java code with line and nextLine
}
“NEXT_LINE”不是一个声明的常量,而是一个无效的代码。我需要用一个有效的 Java 代码替换它,该代码返回集合中的下一个元素,而无需再次递增迭代器。
我找到了这个链接: Java iterator get next without incrementing
在我的例子中,这个解决方案的弱点是如果集合只包含 1 个元素,我必须在我的代码中做太多的更改。如果我的版本有解决方案,则覆盖 1 个元素的情况,因为 nextLine 为空。
我也可以将集合转换为 ArrayList,但只有在我认为没有更好的方法时才会这样做:
ArrayList<T> list = new ArrayList<T>(col);
for (int i=0; i<list.size(); i++) {
T line = list.get(i);
T nextLine = i<list.size()-1 ? list.get(i+1) : null;
// more Java code with line and nextLine
}
【问题讨论】:
-
链表听起来更适合这里
标签: java collections iterator next