The code implements custom iterator, which skips duplicate integers. The array expected is to be sorted.
public class GenericIterator<K> implements Iterator<K> {
private K[] array; // Array will be set here
private int index;
GenericIterator(K[] array) {
this.array = array;
index = 0;
}
/*
*
*
* (non-Javadoc)
*
* @see java.util.Iterator#hasNext() /** Returns <tt>true</tt> if this
* iterator has more elements when traversing the array in the forward
* direction. (In other words, returns <tt>true</tt> if <tt>next</tt> would
* return an element rather than throwing an exception.)
*
* @return <tt>true</tt> if the array iterator has more elements when
* traversing the array in the forward direction.
*/
@Override
public boolean hasNext() {
return !(array.length == index);
}
/*
*
*
* (non-Javadoc)
*
* @see java.util.Iterator#hasNext()
*
* /** Returns the next element in the array. This method may be called
* repeatedly to iterate through the array, or intermixed with calls to
* <tt>previous</tt> to go back and forth. (Note that alternating calls to
* <tt>next</tt> and <tt>previous</tt> will return the same element
* repeatedly.)
*
* @return the next element in the array.
*
*/
@Override
public K next() {
K outputElement = array[index++];
if (index == 0) {
index++;
}
while (hasNext()) {
if (array[index] == array[index - 1]) {
index++;
} else {
break;
}
}
return outputElement;
}
}
GenericIterator
if you only expectInteger
? \$\endgroup\$