Java - 如何初始化堆栈使用另一个现有堆栈?

时间:2017-03-29 00:28:48

标签: java android stack

我已经使用Stack使用类TOKEN的内容,现在我想首先使用堆栈制作并初始化新的Stack

首先我认为是C#的代码,比如

Stack<Token> e_infixTokens = new Stack<Token>(infixTokens);

C#的Stack constuctor使用另一个堆栈参数,但我认为JAVA没有。我是对的吗?

所以,这是我的代码的一部分,

private Stack<Token> infixTokens;
private Stack<Token> postfixTokens;

Formula(String formula){
    this.formula = formula;
    this.infixTokens = new Stack<>();
    this.postfixTokens = new Stack<>();

下面几行,我用这句话。

Stack<Token> e_infixTokens = new Stack<>(infixTokens);

发生错误。错误信息是:

  

Stack中的Stack()无法应用于Java.util.Stack

1 个答案:

答案 0 :(得分:0)

一个简单的方法是这样的。

Stack<String> stackCopy = (Stack<String>) stack1.clone();

此方法来自java.util.Vector.clone(),因此它可能是一个快速实现。

另一个是这样的,测试后非常慢。

Stack<String> stackCopy = new Stack<String>();
for (String string : stack) {
    stackCopy2.add(string);
}

以下代码段比较了两个方法的性能,以便通过另一个现有堆栈初始化堆栈。

public static void main(String[] args) throws Exception {

    Stack<String> stack = new Stack<String>();
    for (int i = 0; i < 1000; i++) {
        stack.push("" + i);
    }


    {
        Stack<String> stackCopy = null;
        long time = System.currentTimeMillis();
        final int numIterations = 100000;
        for (int i = 0; i < numIterations; i++) {
            stackCopy = (Stack<String>) stack.clone();
        }
        System.out.println("stackCopy.get(0) 1 = " + stackCopy.get(0));

        long millis = System.currentTimeMillis() - time;
        System.out.println("Time taken for this: "
                + (millis > 100000 ? (millis / 1000) + " seconds." : millis + " milliseconds."));
    }
    {
        Stack<String> stackCopy = null;
        long time = System.currentTimeMillis();
        final int numIterations = 100000;
        for (int i = 0; i < numIterations; i++) {
            stackCopy = new Stack<String>();
            for (String string : stack) {
                stackCopy.add(string);
            }
        }
        System.out.println("stackCopy.get(0) 2 = " + stackCopy.get(0));

        long millis = System.currentTimeMillis() - time;
        System.out.println("Time taken for this: "
                + (millis > 100000 ? (millis / 1000) + " seconds." : millis + " milliseconds."));
    }
}

控制台结果如下:

stackCopy.get(0) 1 = 0
Time taken for this: 70 milliseconds.
stackCopy.get(0) 2 = 0
Time taken for this: 4098 milliseconds.

此外,呼叫和添加&#39;的速度。并呼吁推动&#39;在第二种方法中类似。

相关问题