I have an ArrayList of Player(s). The array is currently ordered in the player who’ve been logged on first, to the most recent one.
However, i want to sort the ArrayList from the Players positions, high to low. The position is stored in the Player class, retrieved by
player.getX();
I imagine i should have a loop with each item being added to a new ArrayList, but i can’t quite figure out how to actually implement it.
How can i do this?
Loop:
for (int i = 0; i < otherPlayers.size(); i++) {
Player currentPlayer = otherPlayers.get(i);
}
Edit: Added loop example
Either you make Player implementing
Comparableand useCollections.sort(players)or you can directly create a comparator like thisAssuming
player.getX()returns aIntegerEdit
Let’s say you have your
List<Player>namedotherPlayersif you want to sort it directly without writing yourself a loop and the algorithm of sorting, you can rely on the Java built-in methodCollections.sort()to sort it. But this means that either your classPersonimplements theComparableinterface, or you can pass an instance ofComparatoras the second argument of theCollections.sort()method as done above.The
Comparator.compare()method takes two object and does return an integer that says if the first argument is lower than the second, equals or greater. This is how the sorting algorithm will know how to order the elements in your list. So, by creating aComparatorinstance that compare the result ofPlayer.getX()of twoPlayerinstances (the elements of your list), you are able to sort the original list on the position criteria as you asked for it.