2014-02-12 66 views
-2

我是Java新手,我試圖打印出列表中的值,但所有產生的結果都是false。我不確定爲什麼會發生這種情況。List的迭代列表

代碼:

List<Integer> coins = new ArrayList<Integer>(); 
    coins.add(4); 
    coins.add(14); 
    coins.add(2); 
    coins.add(33); 
    coins.add(2); 
    coins.add(7); 
    coins.add(56); 
    coins.add(5); 
    coins.add(8); 

    for (Integer j : coins) { 
     System.out.println(coins.get(j)); 
    } 
+0

你是什麼意思的「它會產生假」? – GGrec

+0

你能澄清*什麼*會產生'假'?這裏沒有什麼應該返回false。 –

+0

它在我的控制檯中顯示爲false – Liondancer

回答

2
for (Integer j : coins) { 
    System.out.println(j); 
} 
+0

我試過了,它仍然產生錯誤 – Liondancer

+1

@Liondancer:如果是這樣,那麼你沒有執行正確的類,或者你正在執行一箇舊的不同版本。 –

+0

@JBNizet你能否解釋一下舊版本的含義? – Liondancer

2
問題

在forEach循環。它應該是:

for (Integer j : coins) { 
      // System.out.println(coins.get(j)); 
      System.out.println(j); 
     } 
0

j的價值將是coins每一個元素,而不是在JavaScript中的索引值的值。

用途:

for (Integer j : coins) { 
    System.out.println(j); 
} 

或者更糟的是在許多方面:

for (int i = 0; i < coins.size(); i++) { 
    System.out.println(coins.get(i)); 
} 
0

當你這樣做:

for (Integer j : coins) 

這就像做:

for (Iterator<Integer> itr = coins.iterator(); itr.hasNext();) { 
    Integer j = itr.next(); 
} 

正如你所看到的,j已經是你想要的值了。

查看docs瞭解更多詳情。