बस स्टैक-क्लास (यह क्लोनबल लागू करता है) के क्लोन() -method का उपयोग करें।
यहाँ JUnit के साथ एक सरल परीक्षण मामला है:
@Test
public void test()
{
Stack<Integer> intStack = new Stack<Integer>();
for(int i = 0; i < 100; i++)
{
intStack.push(i);
}
Stack<Integer> copiedStack = (Stack<Integer>)intStack.clone();
for(int i = 0; i < 100; i++)
{
Assert.assertEquals(intStack.pop(), copiedStack.pop());
}
}
संपादित करें:
tmsimont: यह एक "अनियंत्रित या असुरक्षित संचालन" चेतावनी बनाता है मेरे लिए। इस समस्या को उत्पन्न किए बिना ऐसा करने के लिए कोई भी तरीका?
मैं पहली बार में जवाब दिया कि चेतावनी अपरिहार्य होगा, लेकिन वास्तव में यह <?>
(वाइल्डकार्ड) का उपयोग कर परिहार्य है -typing:
@Test
public void test()
{
Stack<Integer> intStack = new Stack<Integer>();
for(int i = 0; i < 100; i++)
{
intStack.push(i);
}
//No warning
Stack<?> copiedStack = (Stack<?>)intStack.clone();
for(int i = 0; i < 100; i++)
{
Integer value = (Integer)copiedStack.pop(); //Won't cause a warning, no matter to which type you cast (String, Float...), but will throw ClassCastException at runtime if the type is wrong
Assert.assertEquals(intStack.pop(), value);
}
}
मूल रूप से मैं कहना चाहता हूँ आप अभी भी एक अनियंत्रित डाली कर रहे हैं ?
(अज्ञात प्रकार) से Integer
पर, लेकिन कोई चेतावनी नहीं है। व्यक्तिगत रूप से, मैं अभी भी सीधे Stack<Integer>
में डालना पसंद करूंगा और @SuppressWarnings("unchecked")
के साथ चेतावनी दबा दूंगा।
'ढेर ख = (ढेर ) a.clone();' –
Marcelo