Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom Iterator Java?

Tags:

java

iterator

I'm a bit confused about how to implement a custom iterator for a class in Java. I'm required to essentially make an ArrayList without using the inbuilt libraries already available to me. I understand the basics of creating the class but I'm having trouble understanding how to get the Iterator to fit into all of this. I have the following:

I have created a generic class that implements the iterable interface as such it looks something like this:

public class MyArrayList<T> implements Iterable<T> {

I've then got to create a class called MyIterator which according to the wording of the document is a stand alone class. This seems fairly straight forward I make a new class called MyIterator and have it implement the iterator interface so it looks something like this:

public class MyIterator<T> implements Iterator<T>{

My confusion lies in the following. The document says that the Iterator needs to be in it's own class, but how then do I access the data members in "MyArrayList" to fully implement hasNext() and next() for example. As the data members in the underlying array are private (as they should be) I don't see how an external class can fully implement these methods. Am I misunderstanding what is required? By separate class is it still a part of the "MyArrayList" class but defined differently?

I hope that helps, as I said I think I understand what is required of me I just am not exactly sure where my Iterator fits into all of this.

like image 486
Scott Avatar asked Sep 04 '13 09:09

Scott


2 Answers

While the iterator has to be a separate class *, that class will probably have some relation to your Iterable class.

It's often a nested/inner class, precisely because it needs to access the values of the class (and that's what pretty much what inner classes are made for).

Granted, if the Iterable is a List you could implement an Iterator without any "internal" access at all, but you usually still want to get access to the internals for things like checking the modCount (to throw a ConcurrentModificationException when the Iterable is structurally modified while you iterate over it ... and to prevent that exception if you modify it via the Iterator itself).

* you could implement it with your Iterable instance itself, but that would break the contract as soon as the user uses two iterators at the same time.

like image 98
Joachim Sauer Avatar answered Oct 30 '22 02:10

Joachim Sauer


You have to declare your own methods hasNext(), next(), remove(). It has to know how to iterate over your own class, how to go to next element and how to check whether next element exists.

like image 29
Pawel Avatar answered Oct 30 '22 04:10

Pawel