Home > Blockchain >  Iterator takes in string but I need to get elements at even indices?
Iterator takes in string but I need to get elements at even indices?

Time:10-01

Hi I'm creating an EvenIterator where it returns elements at even indices such as:

public class EvenIterator implements java.util.Iterator<String> {

    
private Iterator<String> iter;

public EvenIterator(Iterable<String> iter) {
  this.iter = iter.iterator();
  createEvenListIterator();
}

private void createEvenListIterator() {
  
  LinkedList<String> list = new LinkedList<String>();
  while(iter.hasNext()) {
    String value = iter.next();
    if(value%2 == 0) {
      list.add(value);
    }
  }
  
  iter = list.iterator();
}

public boolean hasNext() {
  return iter.hasNext();
}

public String next() {
  if(iter.hasNext()) {
    return iter.next();
  } else
    throw new NoSuchElementException();
}

public void remove() {
  throw new UnsupportedOperationException();
}

}

and I'm getting an error at if(value%2 == 0) (arguement type error), is there anyway to fix this or workaround this? Thanks.

CodePudding user response:

if(value%2 == 0) is checking if a value is even, but what you need is to check if the index of the value is even. There are a couple of ways to do this, but one way is to add your own counter in the loop.

private void createEvenListIterator() {
  
  LinkedList<String> list = new LinkedList<String>();
  int count = 0;
  while(iter.hasNext()) {
    String value = iter.next();
    if(count % 2 == 0) {
      list.add(value);
    }
    count  ;
  }
  
  iter = list.iterator();
}

Another way, if you're able to switch to using a ListIterator, is to call nextIndex() before iter.next() and get the index directly.

  • Related