I was reading this article about Comparator and Comparable in Java.
https://www.baeldung.com/java-comparator-comparable
Then I tried to do the Comparable code example myself. The goal was to:
I. Create a List:
List<Player> footballTeam = new ArrayList<>();
II. Create and add Player objects to the List
Player player1 = new Player(56, "Yousef",23);
Player player2 = new Player(34, "Sonny",27);
Player player3 = new Player(87, "Jamal",19);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
III. Sort the list, using the Collections' sort() method
Collections.sort(footballTeam);
IV. Print the list
System.out.println("After Sorting : " + footballTeam);
V. End up with this result printed out in the console:
After Sorting : [Steven, John, Roger]
But instead I got the following result:
After sorting: [6.Player@4eec7777, 6.Player@3b07d329, 6.Player@41629346]
I managed to fix the problem by replacing this code:
System.out.println("After Sorting : " + footballTeam);
With a for loop:
for(Player p: footballTeam){
System.out.print(p.getName() + ", ");
}
But I don't think this is the right thing to do. How am I supposed to get the same result as in the article, without a for loop?
All of my code, which tried to replicate the example (2 Classes) https://pastebin.com/u/14nikolov/1/jXx8Grx6