Sadece yığın sınıfının() - yığın sınıfının (cloneable uygular) bir kopyasını kullanın.
Burada JUnit ile basit bir test-durum:
@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());
}
}
Düzenleme:
tmsimont: Bu benim için bir "kontrolsüz ya da güvenli olmayan işlemler" uyarısı oluşturur. Herhangi bir Bu sorunu oluşturmadan bunu yapmak için bir yol?
Ben ilk -typing uyarı kaçınılmaz olurdu, ama aslında o
<?>
(joker) kullanılarak önlenebilir olduğuna cevap
: Temelde
@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);
}
}
Hala denetlenmeyen döküm yapıyoruz derdim ?
'dan (bilinmiyor tipi) Integer
'a kadar, ancak uyarı yok. Şahsen ben hala Stack<Integer>
'a dökülmeyi ve @SuppressWarnings("unchecked")
ile uyarıyı bastırmayı tercih ediyorum.
'Stack b = (Stack ) a.clone();' –
Marcelo