返回给定索引处的stack元素,而无需修改Java中的原始Stack

Ind*_*oob 0 java stack reference

好吧,最近在一次采访中有人问我这个问题,我对此很感兴趣。基本上,我有一个带有一组特定值的堆栈,我想在函数中传递堆栈对象,并在某个索引处返回该值。这里要注意的是,在函数完成之后,我需要未修改的堆栈。这很棘手,因为Java会按值传递对象的引用。我很好奇,如果有纯粹是一个Java的方式做使用push()pop()peek()isempty()和原始数据类型。我反对将元素复制到数组或字符串中。目前,我得到的最干净的是使用克隆,找到下面的代码:

    import java.util.Stack;


public class helloWorld {

public int getStackElement( Stack<Integer> stack, int index ){
    int foundValue=null;//save the value that needs to be returned
    int position=0; //counter to match the index
    Stack<Integer> altStack = (Stack<Integer>) stack.clone();//the clone of the original stack
    while(position<index)
    {
        System.out.println(altStack.pop());
        position++;
    }
    foundValue=altStack.peek();
    return foundValue;
}

    public static void main(String args[]){
        Stack<Integer> stack = new Stack<Integer>();
        stack.push(10);
        stack.push(20);
        stack.push(30);
        stack.push(40);
        stack.push(50);
        stack.push(60);
        helloWorld obj= new helloWorld();
            System.out.println("value is-"+obj.getStackElement(stack,4));
        System.out.println("stack is "+stack);

    }

}
Run Code Online (Sandbox Code Playgroud)

我知道克隆也在复制,但这是我旨在消除的基本缺陷。简而言之,我问我是否真的能够传递栈的值,而不是传递其引用的值。

提前致谢。

PC.*_*PC. 5

int position =5;

Integer result = stack.get(position);
Run Code Online (Sandbox Code Playgroud)

Java文档在这里