【发布时间】:2012-11-10 13:44:56
【问题描述】:
好吧,我最近在一次采访中被问到这个问题,我很感兴趣。基本上我有一个包含一组值的堆栈,我想在函数中传递堆栈对象并返回某个索引处的值。这里的问题是,函数完成后,我需要未修改的堆栈;这很棘手,因为 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);
}
}
我知道克隆也是复制,但这是我要消除的基本缺陷。剥离我是问我是否真的能够传递堆栈的值而不是传递其引用的值。
提前致谢。
【问题讨论】:
-
Java Stack 类扩展了 Vector,所以你可以通过索引获取元素。
-
@nhahtdh:在现实生活中,人们会这样做。不过,我想知道这是否是面试官的目标。
-
@nhahtdh 这是我的第一反应,但正如我所说,或者更确切地说,那个家伙告诉我只使用 push、pop 和 isempty 和原始数据类型。有什么想法吗?
-
@Punkeshwar:只需使用另一个堆栈,然后推送/弹出到下一个堆栈直到到达元素,然后再次推送/弹出以恢复堆栈。
-
@nhahtdh 同意这些是进入某人脑海的最初几个想法。但我认为 THILO 提供的解决方案更接近我想要的。