Search code examples
javaarraylistclone

How to prevent object copying in arraylIst in java


I have an arrayList of object Player. Player has field id, and score. suppose arrayList has player object with id:1, score:200 now when i add player with id:1 and score :300, arraylist have now two object but both with score 200. whereas it should be one with score 100 and one with score. I tried clone() method as arrayList.add(player.clone()) but it did not solve my problem.

code:

Player player= playerService.getPlayerById(id);
player.SetScore(100);
challenge.getPlayerList().add(player.clone());
here challenge is an object which has an attribute playerlist

Please suggest. Thanks.


Solution

  • Without you showing some code, I'm guessing you're adding the same Player object but with different values. If you:

    • Add a Player with id: 1 and score: 100
    • Change the values of that Player object to score: 200
    • Add that object again

    You will have 2 Players in your list with the last values of the Player object.

    Somewhere you need to do a new Player() with new values, not just re-use the same Player object.

    Read this article about call-by-reference, call-by-value: http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html