2014-10-17 74 views
1

是否有可能在下面同時運行2個增強循環?同時運行2個增強for循環

loops1 is a list of integers 1,2,3 
loops2 is a list of integers 5,6,7 


for(loop1 : loops1 && loop2 : loops2) 
{ 
    System.out.println(loop1 + loop2); 
} 


Output in a way : 1 5 2 6 3 7 

任何輸入信息會對您有所幫助。

謝謝!

+0

沒有這樣的結構,因爲你需要處理時的情況這些列表的長度不一樣。在這種情況下你想要你的代碼做什麼? – Joffrey 2014-10-17 07:00:52

+0

如果它們的長度相同。 – Stacker1234 2014-10-17 07:02:25

+0

不可能,即使長度相同 – 2014-10-17 07:02:58

回答

1

是有可能有2增強的同時

這是不可能運行環路,我無法想象的情況時,可以需要它。可以找到文檔here

6

不,這是不可能的。你可以嘗試用迭代器來實現這一目標:

Iterator<Integer> it1 = loops1.iterator(); 
Iterator<Integer> it2 = loops2.iterator(); 

while (it1.hasNext() && it2.hasNext()) 
    System.out.println(it1.next()+it2.next()); 

當然,如果列表不具有相同的長度,你必須決定如何處理長列表的額外整數做。

+2

+1絕對是最接近OP代碼的選項。 – 2014-10-17 07:03:56

1

不,你不能那樣做。你必須有一個複合值列表(例如,每個項目有兩個整數)或者其中的一些,或者當然使用正常的for循環。

0

不,沒有。您可以嘗試執行循環並通過索引進行檢索...或者使用java 8並查看它們的功能結構是否允許您壓縮2個集合,這最終將成爲普通的for-each循環。

0

編號

當列表長度不同時,它將如何工作?

當您編譯for-each循環時,字節代碼只是一個帶有一些額外(隱藏)變量的正常循環。 JAD反編譯器可以用來驗證這一點。

例如,編譯如下:

for(String s : list) 
    System.out.println(s); 

會產生相當的字節碼,因爲這:

int length = list.size(); 
for(int i = 0; i < length; i++) { 
    String s = list.get(i); 
    System.out.println(s); 
} 
0

是有可能有2加強在同一時間運行的循環

它不是可能的。

在這裏你有兩個相同長度的列表。你也想拿出把儘可能

1 5 2 6 3 7 

(First element of list1) (first element of list two)...so on 

這時可以嘗試如下

List<Integer> list1=new ArrayList<>(); 
List<Integer> list2=new ArrayList<>(); 
list1.add(1); 
list1.add(2); 
list1.add(3); 
list2.add(5); 
list2.add(6); 
list2.add(7); 
for(int i=0;i<list1.size();i++){ // both list must in equal size 
    System.out.print(list1.get(i) + " " + list2.get(i)); 
    System.out.print(" "); 
} 

輸出地說:

1 5 2 6 3 7