Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the java for each loop with custom classes?

I think most coders have used code like the following :

 ArrayList<String> myStringList = getStringList(); for(String str : myStringList) {    doSomethingWith(str); } 

How can I take advantage of the for each loop with my own classes? Is there an interface I should be implementing?

like image 731
Geo Avatar asked Jun 10 '09 12:06

Geo


People also ask

How do Java forEach loops work?

How it works? The Java for-each loop traverses the array or collection until the last element. For each element, it stores the element in the variable and executes the body of the for-each loop.

Can we use for-each loop for list in Java?

In java 8 you can use List. forEach() method with lambda expression to iterate over a list.


2 Answers

You can implement Iterable.

Here's an example. It's not the best, as the object is its own iterator. However it should give you an idea as to what's going on.

like image 143
Brian Agnew Avatar answered Sep 21 '22 22:09

Brian Agnew


The short version of for loop (T stands for my custom type):

for (T var : coll) {     //body of the loop } 

is translated into:

for (Iterator<T> iter = coll.iterator(); iter.hasNext(); ) {     T var = iter.next();     //body of the loop } 

and the Iterator for my collection might look like this:

class MyCollection<T> implements Iterable<T> {      public int size() { /*... */ }      public T get(int i) { /*... */ }      public Iterator<T> iterator() {         return new MyIterator();     }      class MyIterator implements Iterator<T> {          private int index = 0;          public boolean hasNext() {             return index < size();         }          public type next() {             return get(index++);         }          public void remove() {             throw new UnsupportedOperationException("not supported yet");          }    } } 
like image 22
Tombart Avatar answered Sep 19 '22 22:09

Tombart