using two independent iterator at the same time!
I am trying to do this homework asking to insert an iterator in a given class code. the iterator meets the following methods:
boolean hasNext()
Object next()
the iterator would have to be able to work in the following brute force pseudo-code that determines if a list has duplicate entries or not. Note there are 2 independent terators at the same time.
boolean containsDuplicates (List L){
Iterator it1 = L.iterator();
Object obj;
while (it1.hasNext()){
obj=it1.next();
Iterator it2 = L.iterator();
while(it2.hasNext())
if(obj.equals(it2.next())
return true;
}
return false;
}
does anybody knows how this iterator can be implemented.
I appreciate the help
[765 byte] By [
naoufela] at [2007-11-27 6:11:03]

do you know where it2 would be pointing when created after the creation of it1?
suppose the list L is [A, B, C, D, E]. the first call to next (obj = it1.next()) in the given method will return A and move the cursor to B. then, the next call to next (it2.next()) will also return A and move the cursor to B. So
it seams to me that it.1.next() and it2.next() would be returning the same object and therefore the method containsDuplicates(List L) would be returning true all the time.
here is the implementation of next()
public Object next() throws NoSuchElementException
{
if (hasNext())
{
Object currentEntry = a[currentIndex];
currentIndex++;
return currentEntry;
}
else
throw new NoSuchElementException("next() was called after
iteration has reached end");
} // end next
thanks again
> does anybody think that I need to change the implementation of next() and/or hasNext() to make the method containsDuplicates() work with two independent iterator at the same time!?
i don't need.
boolean containsDuplicate(List l) {
for (Iterator i1 = l.iterator(), int x = 0; i.hasNext(); x++) {
Object o = i1.next();
for (Iterator i2 = l.listIterator(x+1); i2.hasNext(); ) {
if (o.equals(i2.next())) return true;
}
}
return fals;e
}
Message was edited by:
j_shadinata