Tutorial :Examples of how to add an iterator to a custom class in Java 1.4?



Question:

Could someone give me an example of the best way to add an iterator to a custom class pre Java 5's iterable interface?

Would wrapping a Collection be the best option? Something like

public Iterator iterator() {      return wrappedCollection.iterator();  }  

In my initial post I confused Iterator with Iterable. The end result I am interested in is being able to operate on the custom class with the following.

Iterator it = customClass.iterator();  while (it.hasNext()) {      //do stuff  }  


Solution:1

If you're just wrapping a collection you can use a forwarding method.

public class Custom implements Collection {      Collection c; // create an instance here or in the constructor      ...        // forwarding method      public Iterator iterator()      {          return c.iterator();      }  }  

I think it would be better to implement whatever type of Collection Interface you're wrapping, though, instead of Iterator.


Solution:2

Did you add a method that looks like

public Iterator iterator() {      return new YourCustomIterator(...);  }  

?


Solution:3

It sounds like you just added those methods your class that contains the Collection. In that case, your object is now also your iterator. What you probably meant to do is create a new class that implements Iterator and is instantiated with a clone of your Collection via an iterator() method.


Solution:4

If you just want to expose the iterator of an internal collection you just return that collections iterator. If you want to do more than that, you either have to wrap your own or check out the Apache Commons Collections package which includes quite a few iterator bulider and modifier methods. (Even if you can't use their methods, their implementations should teach you a lot about building iterators.)


Solution:5

You want the collection to have an iterator method that returns an instance of a private Iterator class as needed.

public class IterableTest  {      public Iterator iterator()      {          return new IteratorTest();      }      private class IteratorTest implements Iterator      {          public boolean hasNext(){...}            public Object next(){...}            public void remove(){...}      }  }  


Solution:6

I guess you are looking for something like below

http://karephul.blogspot.com/2009/05/concurrentmodificationexception.html

& yes, idea of inner class is what you are looking for.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »