This is kick-off example how to implement such iterator
, but it's advised also to create or extend appropriate interface
and make this object implementing this interface
for convention.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IterableObject {
private List<String> values = new ArrayList<String>();
public Iterator<String> getIterator(final int index) {
Iterator<String> it = new Iterator<String>() {
private int current = index;
@Override
public void remove() {
// TODO Auto-generated method stub
}
@Override
public String next() {
String value = values.get(current);
current++;
return value;
}
@Override
public boolean hasNext() {
if(values.size() > current){
return true;
}else{
return false;
}
}
};
return it;
}
}
UPDATE
According to comments I've written an Iterator for LinkedList
public Iterator<String> getIterator(final int index) {
Iterator<String> it = new Iterator<String>() {
private Object currentObject = null;
{
/*initialize block where we traverse linked list
that it will pointed to object at place index*/
System.out.println("initialize" + currentWord);
for(int i = 0; currentObject.next != null && i < index; i++, currentObject = currentObject.next)
;
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
@Override
public String next() {
Object obj = currentObject.next;
currentObject = currentObject.next;
return obj;
}
@Override
public boolean hasNext() {
return currentObject.next != null;
}
};
return it;
}
Because Iterator
is object of Anonymous class
we can't use constructor
but can initialise it in initialise block look at this answer: https://stackoverflow.com/a/362463/947111 We traverse it once at the beginning (sorry for C style) so it will point to currentObject
. All remain code is self explained.