Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a bug in java.util.Stack's Iterator?

Today I was trying to push in java.util.Stack class and then use the Iterator to iterate (without using pop) through the items. I was expecting LIFO property but got surprised.

Here is the code that I was trying.

import java.util.*; import java.util.Stack;  public class Main {     public static void main(String[] args) {         RobStack<Integer> rstack = new RobStack<Integer>(); // Correct Implementation         Stack<Integer> jstack = new Stack<Integer>(); // Default Java Implementation         rstack.push(0); jstack.push(0);         rstack.push(1); jstack.push(1);         rstack.push(2); jstack.push(2);         rstack.push(3); jstack.push(3);          System.out.print("Algo Stack: ");         for (int i : rstack)             System.out.print(i + " ");         System.out.print("\nJava Stack: ");         for (int i : jstack)             System.out.print(i + " ");     }  } 

The output the above program is given below:

Algo Stack: 3 2 1 0  Java Stack: 0 1 2 3  

In the above code jstack uses the default Java implementation and rstack uses the implementation provided by Robert Sedgewick for his Algorithm class. I found that Prof. Robert's implementation works fine but the java.util.Stack implementation fails.

Is it a bug or is it by design?

like image 317
vincent mathew Avatar asked Jun 07 '13 20:06

vincent mathew


People also ask

What is import Java Util iterator?

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java. util package.

What is the purpose of iterator in Java?

Iterator in Java is an object used to cycle through arguments or elements present in a collection. It is derived from the technical term “iterating,” which means looping through. Generally, an iterator in Java is used to loop through any collection of objects.

What is iterator in Java collection?

An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways: Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved.


1 Answers

See Bug ID 4475301 : RFE: java.util.Stack.iterator() iterates the wrong way. This behavior is by (bad) design. Java's built-in Stack iterator methods are inherited from other classes, so they don't behave as you'd expect.

like image 91
Bill the Lizard Avatar answered Sep 29 '22 10:09

Bill the Lizard