-1

Possible Duplicate:
Java: What does the colon (:) operator do?

for (CreditCard cc : credit1)

&

if (index instanceof RewardCard)

is ":" and instanceof the same? so I could use?

if (index : RewardCard)

or

for (CreditCard cc instanceof credit1)

if not, can someone explain what the ":" mean?

Community
  • 1
  • 1
Shawn
  • 309
  • 2
  • 5
  • 11

3 Answers3

5

They're not the same: instanceof checks if an instance of an Object is of a certain type. The : in for (CreditCard cc : credit1) is a short way to loop through a List (foreach loop).

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
3

Not at all, they are completely different.

  • for (.. : ..) is a for-each loop
  • instanceof checks the runtime type
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
1
for (CreditCard cc : credit1)

it means

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

and you can use class CreditCard if only it is the same as class declared for given collection.

    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);
    }

So instanceof and for (SomeType obj : SomeCollection) are not even close to be similar

dantuch
  • 9,123
  • 6
  • 45
  • 68