4 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
for Each 循環(huán)的一些限制。
另外,這可以是一種方式:
? ? public class Main
{
? ? public static void main(String[] args) {
? ? String[] arr={"a","b"};
? ? String next="";
? ? String current="";
? ? String prev="";
? ? for(int i=0;i<arr.length;i++){
? ? ? ? //previousElement
? ? ? ? if(i>0){?
? ? ? ? ? ? prev=arr[i-1] ;
? ? ? ? ? ? System.out.println("previous: "+prev);
? ? ? ?}else{
? ? ? ? ? ?prev="none";
? ? ? ? ? System.out.println("previous: "+prev);
? ? ? ? ? ? ? ?}
? ? ? ? ?//currentElement? ? ??
? ? ? ? current=arr[i];
? ? ? ?System.out.println(" current: "+current);
? ? ? ?//nextElement
? ? ? if(i<arr.length-1){
? ? ? ? ? next=arr[i+1];
? ? ? ? ? System.out.println(" next: "+next);
? ? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? ? next="none";
? ? ? ? ? ? ? ? ? System.out.println(" next: "+next);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? }
}
還附加輸出:

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超7個(gè)贊
不。
“foreach”結(jié)構(gòu)使用了Iterator
underlying,它只有一個(gè)next()
andhasNext()
函數(shù)。沒有辦法得到previous()
。
Lists
有一個(gè)ListIterator
允許查看前一個(gè)元素,但“foreach”不知道如何使用它。因此,唯一的解決方案是記住單獨(dú)變量中的前一個(gè)元素,或者僅使用像這樣的簡單計(jì)數(shù)循環(huán):for(int i=0;i< foo.length();i++)
。

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
使用“foreach”只有next()和hasNext()方法,因此它不提供反向遍歷或提取元素的方法。
考慮到您有一個(gè)字符串 ArrayList,您可以使用java.util.ListIterator它提供的方法,例如hasPrevious()和previous()
下面是如何使用它的示例。** 閱讀代碼一側(cè)的注釋,因?yàn)樗褂眠@些方法的重要細(xì)節(jié)。**
ArrayList<String> mylist = new ArrayList<>();
ListIterator<String> myListIterator = mylist.listIterator();
myListIterator.hasNext(); // Returns: true if list has next element
myListIterator.next(); // Returns: next element , Throws:NoSuchElementException - if the iteration has no next element
myListIterator.hasPrevious(); // Returns: true if list has previous element
myListIterator.previous(); //Returns: the previous element in the list , Throws: NoSuchElementException - if the iteration has no previous element
希望這可以幫助。
PS:您應(yīng)該發(fā)布到目前為止所做的代碼,在 stackoverflow 上發(fā)布問題,其中不包含任何內(nèi)容來表明您的努力確實(shí)很糟糕。

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
這樣做的目的是什么?
foreach您可能應(yīng)該使用for循環(huán)和索引來代替 a
for(int i=0;i<lenght;i++) {
list[i-1].dostuff //previous
list[i].dostuff //current
list[i+1].dostuff //next item
}
并且不要忘記檢查下一項(xiàng)和上一項(xiàng)是否存在。
添加回答
舉報(bào)