[英]Need help in Java Array<> libgdx
當我將Array <>項的值分配給臨時變量后更改其值時,主變量值也會更改。
Array<Cards> cards = new Array<Cards>();
//add items to cards
Iterator<Cards> iterator = cards.iterator();
while(iterator.hasNext()){
Cards c = iterator.next();
Cards Temp = c;
//when I change values of temp...the value of c also changes
//overall changing the value of cards
}
有什么方法可以更改Temp的值,而不是c或card?
我目前正在用libgdx開發Android游戲。
您需要復制c
引用的對象。 您當前正在做的只是簡單地創建對同一對象的另一個引用。 根據Card
實現和您的需求,您可以clone
或顯式創建新的Card
。
通過調用.clone()
方法,您可以獲得Object
的副本,而不是對其的引用。
正如@CharlesDurham所說:
.clone()
將產生一個淺表副本,它是Card的新實例,但是如果c有任何對象引用,則新Card將具有與c相同的引用,除非您實現Cloneable接口,否則您可以實現深度克隆。
Array<Cards> cards = new Array<Cards>();
//add items to cards
Iterator<Cards> iterator = cards.iterator();
while(iterator.hasNext()){
Cards c = iterator.next();
Cards Temp = c.clone();
//when i change values of temp...the value of c also changes
//overall changing the value of cards
}
或者,您可以像下面這樣制作new Cards(c)
:
Array<Cards> cards = new Array<Cards>();
//add items to cards
Iterator<Cards> iterator = cards.iterator();
while(iterator.hasNext()){
Cards c = iterator.next();
Cards Temp = new Cards(c);
//when i change values of temp...the value of c also changes
//overall changing the value of cards
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.