わかりました、私は最近インタビューでこれを尋ねられました、そして私は興味をそそられました. 基本的に、特定の値のセットを持つスタックがあり、スタック オブジェクトを関数に渡し、特定のインデックスで値を返したいと考えています。ここでの問題は、関数が完了した後、変更されていないスタックが必要だということです。Java はオブジェクトの参照を値で渡すため、注意が必要です。push()
、、、およびプリミティブ データ型pop()
を使用する純粋な Java の方法があるかどうか、私は興味があり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);
}
}
クローン作成もコピーであることは理解していますが、それは私が取り除こうとしている基本的な欠陥です。簡略化して、参照の値を渡す代わりに、実際にスタックの値を渡すことができるかどうかを尋ねています。
前もって感謝します。