java.util.Stack 的迭代器中是否有错误?有错误、器中、迭代、java

2023-09-07 10:03:33 作者:右手年华,左手青春

今天我试图推入 java.util.Stack 类,然后使用 Iterator 对项目进行迭代(不使用 pop).我期待 LIFO 财产,但感到惊讶.

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("
Java Stack: ");
        for (int i : jstack)
            System.out.print(i + " ");
    }

}

上述程序的输出如下:

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

在上面的代码中,jstack 使用默认的 Java 实现,rstack 使用 Robert Sedgewick 为他的算法类提供的实现.我发现 Robert 教授的实现工作正常,但 java.util.Stack 实现失败.

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.

这是一个错误还是设计?

推荐答案

参见 错误 ID 4475301:RFE:java.util.Stack.iterator() 迭代错误的方式.这种行为是(不良)设计的.Java 的内置 Stack 迭代器方法继承自其他类,因此它们的行为与您预期的不同.

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.