如何用Java复制堆栈? [英] How do I copy a stack in Java?

查看:354
本文介绍了如何用Java复制堆栈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个堆栈A,我想创建一个与堆栈A相同的堆栈B.我不希望堆栈B只是一个指向A的指针 - 我实际上想要创建一个包含A的新堆栈与堆栈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.

谢谢!

推荐答案

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

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

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

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());
    }
}

编辑:


tmsimont:这会为我创建一个未经检查或不安全的操作警告。任何
的方法都可以做到这一点而不会产生这个问题?

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

我起初回应说警告是不可避免的,但实际上使用<?> (通配符)-typing可以避免:

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);
    }
}

基本上我会说你还在做未经检查从(未知类型)转换为整数,但没有警告。就个人而言,我仍然倾向于直接投入 Stack< Integer> 并使用 @SuppressWarnings(unchecked)

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").

这篇关于如何用Java复制堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆