简体   繁体   中英

why we don't create new iterator object in this case?

this really confused me very much. Basically, I want to print the elements of two 1d-vector alternatively. And I found the solution attached below wrote by others. In the main method, we call zigzagIterator.next() to print the number returned by int num = iter.next()

In the next() method, it seems that it created a new iter object every time when the next() method has been called. But when I debug, I found only two iterator object has been created. one is for a1, another is for a2. So that the cursor in each iterator object keeps its memory to iterate until the end.

It just doesn't make sense to me that Iterator<Integer> iter = deque.pollLast() has been called several times but only two objects created. Hope someone can help!! thanks a lot.

public class ZigzagIterator {
Deque<Iterator<Integer>> deque;

public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
    deque = new LinkedList<Iterator<Integer>>();
    if(v1.size() != 0) deque.offerFirst(v1.iterator());
    if(v2.size() != 0) deque.offerFirst(v2.iterator());
}

public int next() {
    Iterator<Integer> iter = deque.pollLast();
    int num = iter.next();
    if(iter.hasNext()) deque.offerFirst(iter);
    return num;
}

public boolean hasNext() {
    return (deque.size() != 0);
}
public static void main(String[] args) {
    // TODO Auto-generated method stub
    List<Integer> a1= new ArrayList<Integer>();
    a1.add(1);
    a1.add(2);
    a1.add(12);
    List<Integer> a2= new ArrayList<Integer>();
    a2.add(3);
    a2.add(4);
    a2.add(5);
    a2.add(6);
    ZigzagIterator zigzagIterator=new ZigzagIterator(a1, a2);
    while (zigzagIterator.hasNext()) 
    System.out.println(zigzagIterator.next());
}
}

Its because the object reference Remains the same, while the New objects created are being assigned to the 2 references (v1,v2) . thus last 2 object will get the 2 references resulting in 2 usable objects while others are garbage collectible

visit the https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM