mariusz-
mariusz-

Reputation: 209

Strange behaviour with Collections - sort method

I have strange problem with sorting my list.

At first, I have a custom class with

private List<Player> players;

So, in players are some items, for example 2 - "Player 1" and "Player 2".

It is Player class basically:

public class Player {

    private String name;
    private int points = 0; 
}

I have a function used for sorting players (comparing points):

public String getActualRanking() {

    for(int z = 0; z < players.size(); z++) {
        Log.d("COLSORT", players.get(z).getName());
    }

    String message = "";

    List<Player> temp = players;
    Collections.sort(temp, new Comparator<Player>() {
        @Override
        public int compare(Player player, Player t1) {
            return Integer.valueOf(t1.getPoints()).compareTo(player.getPoints());
        }
    });

    for(int i = 0; i < temp.size(); i++) {
        message += Integer.toString(temp.get(i).getPoints()) + " pkt - " + temp.get(i).getName() + "\n";
    }


    for(int z = 0; z < players.size(); z++) {
        Log.d("COLSORT", players.get(z).getName());
    }

    return message;
}

Why there is 2 Log.d? Because first log is:

D/COLSORT﹕ Player 1
D/COLSORT﹕ Player 2

But second is:

D/COLSORT﹕ Player 2
D/COLSORT﹕ Player 1

The question is: why? Why Collections.sort do sorting on "players" list if I created "temp" list to be sorted and "players" are not used in this function anymore? I really don't understand that behaviour :/

Upvotes: 0

Views: 114

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198023

List<Player> temp = players;

This does not create a copy of the players list. temp and players are now referring to the same list. There is no difference between temp and players anymore.

If you want to make a copy so that temp can be sorted without changing players, write

List<Player> temp = new ArrayList<>(players);

Upvotes: 2

Related Questions