I am suppose to write a ComparePlayers class that implements the Comparator<Player> interface. It should compare players by number of games played (and then by alphabetical order of surname if the number of games played is the same). This is what I wrote , it is the general idea i could grasp, and I was wondering how do I improvise this code so it would return the players name instead of 1 or -1. Am not sure how do i go about it.
import java.util.*;
public class ComparePlayers implements Comparator<Player>
{
public int compare(Player ply1,Player ply2)
{
if(ply1.gPlayed()>ply2.gPlayed())
{
return 1;
}else if(ply1.gPlayed()==ply2.gPlayed())
{
return ply1.compareTo(ply2);
}else
{
return -1;
}
}
}
and I am suppose to implement a new Constructor for the Club class that takes the Comparator<Player> parameter. What I wrote is as followed.
Is it correct? How do I change it?
public Club(Club c)
{
ComparePlayers cPlyr = new ComparePlayers();
clubPlayers = c.clubPlayers;
for (int num1=0; num1<clubPlayers.size()-1; num1++)
{
for (int num2=1; num2<clubPlayers.size(); num2++)
{
if (cPlyr.compare(clubPlayers.get(num1), clubPlayers.get(num2))==-1)
{
Player temp = clubPlayers.get(num1);
clubPlayers.set(num1, clubPlayers.get(num2));
clubPlayers.set(num2, temp);
}
}
}
}
Cheers