Question

I ran across an interesting use of the ":" operator while writing some unit tests for somebody else's code. It looks like this:

for(Class classInstance : instanceOfOtherClass){

//Do some irrelevant stuff

}

I have never seen the ":" operator used by itself without the "?", like it would be when writing a ternary statement. I've done a fair amount of Googling, and can't seem to find any sensible answers regarding how I should read this...

Am I over-complicating this? Has anyone seen it before?

Was it helpful?

Solution

For future reference, had you typed:

java 7 for loop :

into google, the second result would have helped you. To your defense, if you don't put the "7" there, it would have been more difficult to find a solution (not because it was introduced in java 7, it was in java 5, but because if it's currently supported, then putting a 7 gives you a higher probability of finding up-to-date documentation). This is an example of an enhanced for loop or a for-each loop.

In short:

EnhancedForStatement:

for ( FormalParameter : Expression ) Statement

where the Expression must be iterable or an array type.

In simpler terms (array example, but note that anything that implements Iterable can be used):

String[] words = new String[]{"This","is","the","end"};

for (int i = 0; i < words.length; i++)
{
      System.out.println(words[i]);
}

written with a for-each loop is:

for (String s : words)
{
      System.out.println(s);
}

If you're wondering about efficiency, check this post out.

OTHER TIPS

It's called for each

for(Class object : Objects){
    //it will iterate through all the objects contained in Objects
    //Objects can be an array, a list, etc.
    //object Class/Type must match the class of the objects contained in Objects

}

For example this will iterate the chars in a String

for(char c : string.toCharArray()){
    System.out.println(c);
}

Here you'll find a comparison between this for and the classic one:

Fastest way to iterate an Array in Java: loop variable vs enhanced for statement

// Infinite
 for ( ; ; ) {

   // Code
 }

//Array<Object>
 int[] numbers = 
         {1,3,6,9,12,15,18};
     for (int item : numbers) {
         System.out.println("Count is: " + item);
     }

//List<Object>
  ArrayList<Object> objectList ;//I assume it's perfectly initialized and filled

  for (Object temp : objectList) {
    System.out.println(temp);
}

First, it can be used with arrays. Consider an array of objects of type MyClass:

MyClass[] objects = new MyClass[SIZE];

Iterate like so:

for(MyClass object : objects) {
  // do something with the individual object.
}

Secondly, you can use it with iterable collections. Consider a class MyClass of individual elements and make a collection of them by defining a subclass of Iterable:

class MyClassList implements Iterable<MyClass> {
  // define necessary methods to implement the Iterable interface!
}

Now we can make a collection:

MyClassList objects = new MyClassList();
// fill the collection somehow.

And iterate:

for(MyClass object : objects) {
  // do something with the individual object
}

Finally, note that the main disadvantage of this construct is that you don't have access to an element's position in the iteration. For a given object that you are processing, if you want to know its position you should either use a for loop:

for(int i = 0; i < objects.size(); i++) {
  // Here we have access to the position i
}

Or use a makeshift index:

int i = 0;
for(MyClass object : objects) {
  // do something with access to position i
  i++;
}

I personally do not like the last hack, and would just fall back to the classic for loop. Hope this helps!

Example of use:

String[] words = {"one", "two", "three", "one", "two", "three"};
for(String one : words){
System.out.println("found it");
}

Now, I bet you think that when you run this it will print "found it" to the screen twice. Once, for each instance of String = "one"...but you'd be wrong. What this will print is "found it" SIX times! The reason is that it is searching through one object of instances of another! Because there are six instances of String objects inside of the String Array, it will perform the statement inside of the enhanced for loop that many times. Hopefully, this colorful explanation made it simpler to understand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top