mpz mpz - 5 months ago 6
Java Question

Java element of a new List using a Set

I have the method

changePlayer()
that sets another element from the set
players
from the class
Model
as the value of the field
currentPlayer
; since i can't get elements directly from a set i created a new ArrayList using that set,
what i want to know is that if that element created is still using the reference from the old one or has a new reference and therefore any change i make to it will not change the original element from the set created in
Model
,

public class Model extends Observable<Change> {

private Set<Player> players;
private Player currentPlayer;
public Model(){
players = new HashSet<Player>();
}

public void addPlayer(Player player){
currentPlayer = player;
this.players.add(player);
}
public Set<Player> getPlayers(){
return Collections.unmodifiableSet(this.players);
}

public Player getCurrentPlayer() {
return currentPlayer;
}
public void setCurrentPlayer(Player currentPlayer) {
this.currentPlayer = currentPlayer;
}

}
public void changePlayer(Model game){
Player player2 = new Player(0);//the id in this case is 0
List<Player> playersList = new ArrayList<Player>(game.getPlayers());
//this is the part of the code where i create a list using the set
Player player = game.getCurrentPlayer();
int id= player.getId();
for(int i=0;i<playersList.size();i++){
if (id == playersList.get(i).getId()){
id++;
if(id<=playersList.size()){
for(int j=0;j<playersList.size();j++){
if(id ==playersList.get(j).getId()){
player2 = playersList.get(j);
}
}
}else{
id=1;
for(int j=0;j<playersList.size();j++){
if(id ==playersList.get(j).getId()){
player2 = playersList.get(j);
}
}
}

}
}

game.setCurrentPlayer(player2);

}


To understand better my question i'll you an example, let's say that i create two player objects and add it to the set
players


Player playerA = new Player(1);
Player playerB = new Player(2);


then i set
playerA
as the
currentPlayer
, so what i want to know is that when i run the method it will set
playerB
as the
currentPlayer
or it's gonna create a new copy and any change i make to it will not affect
playerB
?

Answer

You're only creating a new List, but the references in the List are still the same references(the reference values are copied but the values still point to the same instances of Player, which is similar to no matter how many times of your passport number is copied, the number still identifies you). Thus, if you change the referenced Player in your method, you're actually changing the Player in your original Model, which is obvious, since you haven't created any new Player in your method body, have you? The Player instances won't just magically be copied since they are not primitive types. There will be only one exception that you're actually cloning all the Player instances, which is in your game.getPlayers(), you actually deep copied every Player. However, this is not what programmers would usually do.