Provide an iterator over the contents of two lists simultaneously?

前端 未结 11 2044
逝去的感伤
逝去的感伤 2020-12-03 04:45

Suppose I have this:

public class Unit {

    ...

    List mobileSuits;
    List pilots;

    ...
}
         


        
11条回答
  •  春和景丽
    2020-12-03 05:32

    Anyway, the problem is that I can't really return just a single object from next(), and I also can't have a Iterator take more than one type. So, any thoughts?

    Obviously you are going to need a light-weight "pair" class. This is roughly analogous to the Map.Entry inner class.

    Here's a rough cut at a generic solution:

    public class ParallelIterator  implements Iterator> {
    
        public class Pair {
            private final TT1 v1;
            private final TT2 v2;
            private Pair(TT1 v1, TT2 v2) { this.v1 = v1; this.v2 = v2; }
            ...
        }
    
        private final Iterator it1;
        private final Iterator it2;
    
        public ParallelIterator(Iterator it1, Iterator it2) { 
            this.it1 = it1; this.it2 = it2;
        }
    
        public boolean hasNext() { return it1.hasNext() && it2.hasNext(); }
    
        public Pair next() {
            return new Pair(it1.next(), it2.next());
        }
    
        ...
    
    }
    

    Note: this doesn't explicitly deal with cases where the lists have different lengths. What will happen is that extra elements at the end of the longer list will be silently ignored.

提交回复
热议问题