Java 如何访问 ArrayList 中的上一个/下一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19850468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I access the previous/next element in an ArrayList?
提问by nomnom
I iterate through an ArrayList this way:
我以这种方式遍历 ArrayList:
for (T t : list){
...
}
When I did this, I never thought I had to access the previous and next elements of this element. Now my code is huge. It costs a lot if I rewrite it with:
当我这样做时,我从没想过我必须访问这个元素的上一个和下一个元素。现在我的代码很大。如果我用以下方式重写它会花费很多:
for (int i = 0; i < list.size(); i++){
...
}
采纳答案by nomnom
I think I found the solution it is simple in fact, but I cannot delete this post already because it has answers..
我想我发现解决方案实际上很简单,但我不能删除这篇文章,因为它有答案..
I just added T t = list.get(i);
in the second for-loop, all other code remains unchanged.
我刚刚T t = list.get(i);
在第二个 for 循环中添加,所有其他代码保持不变。
回答by Hyman
No, the for-each loop is meant to abstract the Iterator<E>
which is under the hood. Accessing it would allow you to retrieve the previous element:
不,for-each 循环旨在抽象Iterator<E>
引擎盖下的内容。访问它可以让你检索上一个元素:
ListIterator<T> it = list.listIterator();
while (it.hasNext()) {
T t = it.next();
T prev = it.previous();
}
but you can't do it directly with the for-each.
但是你不能直接用 for-each 来做。
回答by Pedro Vítor
You can access any element in ArrayList by using the method get(index).
您可以使用 get(index) 方法访问 ArrayList 中的任何元素。
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<Integer>();
array.add(1);
array.add(2);
array.add(3);
for(int i=1; i<array.size(); i++){
System.out.println(array.get(i-1));
System.out.println(array.get(i));
}
}
}
回答by rndStr
As an answer to the title, rather than the question(with considerations to concurrent operations)...
作为标题的答案,而不是问题(考虑到并发操作)......
T current;
T previous;
{
ListIterator<T> lit = list.listIterator(index);
current = lit.hasNext()?lit.next():null;
previous = lit.hasPrevious()?lit.previous():null;
}
回答by Kenzo1
I found a solution too. It was next.
我也找到了解决办法。是下一个。
For next: letters.get(letters.indexOf(')')+1)
接下来: letters.get(letters.indexOf(')')+1)
For previous: letters.get(letters.indexOf(')')-1)
对于以前的: letters.get(letters.indexOf(')')-1)