小编Ind*_*oob的帖子

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

好吧,最近在一次采访中有人问我这个问题,我对此很感兴趣。基本上,我有一个带有一组特定值的堆栈,我想在函数中传递堆栈对象,并在某个索引处返回该值。这里要注意的是,在函数完成之后,我需要未修改的堆栈。这很棘手,因为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)); …
Run Code Online (Sandbox Code Playgroud)

java stack reference

0
推荐指数
1
解决办法
2万
查看次数

标签 统计

java ×1

reference ×1

stack ×1