2012-07-26 102 views
-1

可能重複:
Java: What does the colon (:) operator do?的instanceof在Java

for (CreditCard cc : credit1) 

&

if (index instanceof RewardCard) 

是 「:」 和的instanceof一樣嗎?所以我可以使用?

if (index : RewardCard) 

for (CreditCard cc instanceof credit1) 

如果沒有,可以有人解釋一下 「:」 是什麼意思?

+0

你嘗試它是相似的? – cheeken 2012-07-26 04:00:21

回答

5

它們不一樣:instanceof檢查一個對象的實例是否屬於某種類型。在for (CreditCard cc : credit1)中的:是通過列表循環的簡短方式(foreach循環)。

3

完全不同,它們完全不同。

1
for (CreditCard cc : credit1) 

這意味着

for each CreditCard IN credit1, lets call it cc and use it somehow 

,你可以使用類信用卡式,只要它是同級申報給定收集。

List<Parent> list = new ArrayList<Parent>(); 
    list.add(new Parent()); 
    list.add(new Child()); 

    for (Child parent : list) { // compilation error! - Type mismatch: cannot convert from element type Parent to Child 
     System.out.println(parent); 
    } 

所以instanceoffor (SomeType obj : SomeCollection)甚至沒有接近