Search code examples
javaarraydeque

Itearator in Array Deque Data Structure in Java


static ArrayDeque<Integer> bfs = new ArrayDeque<Integer>();
static Iterator<Integer> revbfs = new ArrayDeque<Integer>();

revbfs=bfs.descendingIterator();

very quick question. I want to return the bfs in reverse order. There is the descendingIteartor method, I'm just not sure what it's returning. What would revbfs be in this case? How am I to use the method to get to my reverse order?


Solution

  • Well, this is very easy to test with this code:

    public class Test {
        static Deque<Integer> bfs = new ArrayDeque<>();
    
        public static void main(String[] args) {
            bfs.add(1);
            bfs.add(2);
            bfs.add(3);
    
            Iterator<Integer> revbfs = bfs.descendingIterator();
            while(revbfs.hasNext()) {
                System.out.println(revbfs.next());
            }
            // output is 3, 2, 1
        }
    
    }
    

    Also, the official docs can be very helpful, in this case:

    Iterator descendingIterator()

    Returns an iterator over the elements in this deque in reverse sequential order. The elements will be returned in order from last (tail) to first (head).

    Try searching, reading and testing whenever you are unsure of certain class/method behavior.