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

Is there a bug in java.util.Stack#39;s Iterator?(java.util.Stack 的迭代器中是否有错误?)
本文介绍了java.util.Stack 的迭代器中是否有错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我试图推入 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.

这篇关于java.util.Stack 的迭代器中是否有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)