Cooled Knight
Cooled Knight

Reputation: 31

Need help in Java Array<> libgdx

When I change the values of a item of Array<> after assigning it to a temporary variable, the main variable values also changes.

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
}

Is there any way I can change the value of Temp and not c or cards?

I am currently making a game in libgdx for Android.

Upvotes: 1

Views: 466

Answers (2)

Blake Yarbrough
Blake Yarbrough

Reputation: 2316

By calling the .clone() method you can get a copy of the Object rather than a reference to it.

As @CharlesDurham said :

.clone() will produce a shallow copy, it's a new instance of Card but if c has any object references the new Card will have the same references as c, Unless you implement the Cloneable interface, then you can implement deep cloning.

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
}

Alternately you can make a new Cards(c) like so:

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
}

Upvotes: 1

Kon
Kon

Reputation: 10810

You need to make a copy of the object referenced by c. What you're currently doing is simply creating another reference to the same object. Depending on the the Card implementation and your needs, you can do a clone or create a new Card explicitly.

Upvotes: 5

Related Questions