Rajat Gupta
Rajat Gupta

Reputation: 26617

Implementing such an iterator?

I have a list (an ArrayList, infact) of type HColumn<ColName, ColValue>. Now I want to implement an iterator() that iterates over this collection such that on iteration it gives out the corresponding ColValue from each HColumn.

This object HColumn<ColName, ColValue> is defined in an external library used by my java application.

How can I do that, if possible ?

Currently, to create such an iterable, I had been creating a new list altogether containing corresponding ColValues which I guess is not good thing, in terms of performance & efficiency.

Upvotes: 0

Views: 132

Answers (1)

Bozho
Bozho

Reputation: 597362

As suggested by @jordeu:

public class IteratorColValueDecorator implements Iterator<ColValue> {
      private Iterator<HColumn<ColName, ColValue>> original;
      //constructor taking the original iterator
      public ColValue next() {
           return original.next().getValue();
      }
      //others simply delegating
}

Or, my original suggestion:

public class ColValueIterator implements Iterator<ColValue> {
    private List<HColumn<ColName, ColValue>> backingList;
    //constructor taking List<...>
    int currentIndex = 0;
    public ColValue next() {
        return backingList.get(currentIndex++).getColumn();
    }
    //hasNext() implemented by comparing the currentIndex to backingList.size();
    //remove() may throw UnsupportedOperationException(), 
    //or you can remove the current element
}

Upvotes: 4

Related Questions