4 回答

TA貢獻1815條經驗 獲得超10個贊
for Each 循環的一些限制。
另外,這可以是一種方式:
? ? 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貢獻1794條經驗 獲得超7個贊
不。
“foreach”結構使用了Iterator
underlying,它只有一個next()
andhasNext()
函數。沒有辦法得到previous()
。
Lists
有一個ListIterator
允許查看前一個元素,但“foreach”不知道如何使用它。因此,唯一的解決方案是記住單獨變量中的前一個元素,或者僅使用像這樣的簡單計數循環:for(int i=0;i< foo.length();i++)
。

TA貢獻1804條經驗 獲得超2個贊
使用“foreach”只有next()和hasNext()方法,因此它不提供反向遍歷或提取元素的方法。
考慮到您有一個字符串 ArrayList,您可以使用java.util.ListIterator它提供的方法,例如hasPrevious()和previous()
下面是如何使用它的示例。** 閱讀代碼一側的注釋,因為它包含使用這些方法的重要細節。**
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:您應該發布到目前為止所做的代碼,在 stackoverflow 上發布問題,其中不包含任何內容來表明您的努力確實很糟糕。

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