java 返回给定索引处的堆栈元素而不修改Java中的原始堆栈
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13507978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return the stack element at a given index without modifying the original Stack in Java
提问by IndianNoob
Ok I was recently asked this in an interview, and I am intrigued. Basically I have a stack with a certain set of values, I want to pass the stack object in a function and return the value at certain index. The catch here is that after the function is complete, I need the stack unmodified; which is tricky because Java passes reference by value for objects. I am curious if there is purely a java way to do using push()
, pop()
, peek()
, isempty()
and primitive data type. I am against copying the elements into an array or string. Currently the cleanest I have got is using clone, find the code below:
好吧,我最近在一次采访中被问到这个问题,我很感兴趣。基本上我有一个带有一组特定值的堆栈,我想在函数中传递堆栈对象并返回特定索引处的值。这里的问题是,在函数完成后,我需要未修改的堆栈;这很棘手,因为 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);
}
}
I understand that cloning is also copying, but that's the basic flaw I am aiming to remove. Stripped down I am asking if I would be actually be able to pass the stack's value instead of passing the value of its reference.
我知道克隆也是复制,但这是我旨在消除的基本缺陷。精简后我在问我是否真的能够传递堆栈的值而不是传递其引用的值。
Thanks in advance.
提前致谢。
回答by Thilo
If you cannot use another stack, you can cheat and abuse a local variable on the call stack for the same purpose by making a recursive method:
如果您不能使用另一个堆栈,您可以通过创建递归方法来欺骗和滥用调用堆栈上的局部变量以达到相同目的:
public static <T> T getStackElement(Stack<T> stack, int index) {
if (index == 0) {
return stack.peek();
}
T x = stack.pop();
try {
return getStackElement(stack, index - 1);
} finally {
stack.push(x);
}
}