如何在 Java 中复制堆栈?

发布于 2024-12-12 09:40:58 字数 122 浏览 1 评论 0原文

我有一个堆栈 A,我想创建一个与堆栈 A 相同的堆栈 B。我不希望堆栈 B 只是指向 A 的指针 - 我实际上想创建一个包含相同元素的新堆栈 B作为堆栈 A,其顺序与堆栈 A 相同。堆栈 A 是字符串堆栈。

谢谢!

I have a stack A and I want to create a stack B that is identical to stack A. I don't want stack B to simply be a pointer to A -- I actually want to create a new stack B that contains the same elements as stack A in the same order as stack A. Stack A is a stack of strings.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

眼泪都笑了 2024-12-19 09:40:58

只需使用 Stack 类的 clone() 方法(它实现 Cloneable)。

这是一个使用 JUnit 的简单测试用例:

@Test   
public void test()
{
    Stack<Integer> intStack = new Stack<Integer>();
    for(int i = 0; i < 100; i++)        
    {
        intStack.push(i);
    }

    Stack<Integer> copiedStack = (Stack<Integer>)intStack.clone();

    for(int i = 0; i < 100; i++)            
    {
        Assert.assertEquals(intStack.pop(), copiedStack.pop());
    }
}

编辑:

tmsimont:这为我创建了“未经检查或不安全的操作”警告。任何
如何在不产生此问题的情况下做到这一点?

我一开始回答说警告是不可避免的,但实际上可以使用 (通配符) -打字来避免它:

@Test
public void test()
{
    Stack<Integer> intStack = new Stack<Integer>();
    for(int i = 0; i < 100; i++)
    {
        intStack.push(i);
    }

    //No warning
    Stack<?> copiedStack = (Stack<?>)intStack.clone();

    for(int i = 0; i < 100; i++)
    {
        Integer value = (Integer)copiedStack.pop(); //Won't cause a warning, no matter to which type you cast (String, Float...), but will throw ClassCastException at runtime if the type is wrong
        Assert.assertEquals(intStack.pop(), value);
    }
}

基本上我会说你仍然在进行未经检查的转换 < code>?(未知类型)转换为 Integer,但没有警告。就我个人而言,我仍然更喜欢直接转换为 Stack 并使用 @SuppressWarnings("unchecked") 抑制警告。

Just use the clone() -method of the Stack-class (it implements Cloneable).

Here's a simple test-case with JUnit:

@Test   
public void test()
{
    Stack<Integer> intStack = new Stack<Integer>();
    for(int i = 0; i < 100; i++)        
    {
        intStack.push(i);
    }

    Stack<Integer> copiedStack = (Stack<Integer>)intStack.clone();

    for(int i = 0; i < 100; i++)            
    {
        Assert.assertEquals(intStack.pop(), copiedStack.pop());
    }
}

Edit:

tmsimont: This creates a "unchecked or unsafe operations" warning for me. Any
way to do this without generating this problem?

I at first responded that the warning would be unavoidable, but actually it is avoidable using <?> (wildcard) -typing:

@Test
public void test()
{
    Stack<Integer> intStack = new Stack<Integer>();
    for(int i = 0; i < 100; i++)
    {
        intStack.push(i);
    }

    //No warning
    Stack<?> copiedStack = (Stack<?>)intStack.clone();

    for(int i = 0; i < 100; i++)
    {
        Integer value = (Integer)copiedStack.pop(); //Won't cause a warning, no matter to which type you cast (String, Float...), but will throw ClassCastException at runtime if the type is wrong
        Assert.assertEquals(intStack.pop(), value);
    }
}

Basically I'd say you're still doing an unchecked cast from ? (unknown type) to Integer, but there's no warning. Personally, I'd still prefer to cast directly into Stack<Integer> and suppress the warning with @SuppressWarnings("unchecked").

青丝拂面 2024-12-19 09:40:58

Stack 扩展了 Vector,因此您可以新建一个新的 Stack 并使用 .addAll(...)复制项目:

Stack<Type> newStack = new Stack<Type>();
newStack.addAll(oldStack);

Stack extends Vector, so you can just new up a new Stack and use .addAll(...) to copy the items:

Stack<Type> newStack = new Stack<Type>();
newStack.addAll(oldStack);
梦幻之岛 2024-12-19 09:40:58

Stack 类是摘要列表

只需将其视为 AbstractList,使用 get(int index) 方法迭代堆栈中的元素(从 0 到列表/堆栈的长度),然后将元素添加到新堆栈中。

这不会复制元素 - 它将把元素添加到新堆栈中。如果您还需要复制元素,则需要更深入地创建元素的副本,并将它们添加到新堆栈中。

您可以使用克隆来进行完整(或“深层”)复制 方法,但请注意该对象必须实现 可克隆接口,以便获取对象的深层副本

The Stack class is a sub-class of AbstractList.

Simply treat it like an AbstractList, iterate through the elements in the stack using the get(int index) method, from 0 to the length of your list/stack, and add the elements to the new stack.

This won't copy the elements - it will add the elements to the new stack. If you need to copy the elements as well, you'll need to go another level deep and create copies of the elements, and add those to the new stack.

You can do full (or "deep") copies, by using the clone method, but note that the object must implement the Clonable interface in order to get deep copies of objects.

年少掌心 2024-12-19 09:40:58

您想要使用 克隆方法。

You want to use the clone method.

々眼睛长脚气 2024-12-19 09:40:58
 /**
     * Copy constructor for the Stack class
     * @param original the Stack to copy
     * @postcondition a new Stack object which is
     * an identical, but distinct, copy of original
     */
    public Stack(Stack<T> original) {
        if (original.length == 0)
        {
            length = 0;
            top = null;
        } else
        {
            Node temp = original.top;
            while (temp != null)
            {
                push(temp.data); // inserts into this
                temp = temp.next;
            }
            temp = top;
            temp = temp.next;
            top.next = null;
            while (temp != null){
                push(temp.data); // inserts into this
                temp = temp.next;
            }

        }
    }
 /**
     * Copy constructor for the Stack class
     * @param original the Stack to copy
     * @postcondition a new Stack object which is
     * an identical, but distinct, copy of original
     */
    public Stack(Stack<T> original) {
        if (original.length == 0)
        {
            length = 0;
            top = null;
        } else
        {
            Node temp = original.top;
            while (temp != null)
            {
                push(temp.data); // inserts into this
                temp = temp.next;
            }
            temp = top;
            temp = temp.next;
            top.next = null;
            while (temp != null){
                push(temp.data); // inserts into this
                temp = temp.next;
            }

        }
    }
嘿看小鸭子会跑 2024-12-19 09:40:58
 /**
 * Copy constructor for the Stack class
 * @param original the Stack to copy
 * @postcondition a new Stack object which is
 * an identical, but distinct, copy of original
 */
public Stack(Stack<T> original) {
    if (original.length == 0)
    {
        length = 0;
        top = null;
    } else
    {
        Node temp = original.top;
        while (temp != null)
        {
            push(temp.data); // inserts into this
            temp = temp.next;
        }
        temp = top;
        temp = temp.next;
        top.next = null;
        while (temp != null){
            push(temp.data); // inserts into this
            temp = temp.next;
        }

    }
}
 /**
 * Copy constructor for the Stack class
 * @param original the Stack to copy
 * @postcondition a new Stack object which is
 * an identical, but distinct, copy of original
 */
public Stack(Stack<T> original) {
    if (original.length == 0)
    {
        length = 0;
        top = null;
    } else
    {
        Node temp = original.top;
        while (temp != null)
        {
            push(temp.data); // inserts into this
            temp = temp.next;
        }
        temp = top;
        temp = temp.next;
        top.next = null;
        while (temp != null){
            push(temp.data); // inserts into this
            temp = temp.next;
        }

    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文