Hi I'm reasonably new to programming and I am having difficulty with my compare method, I have several classes, my initial issue is with my parent class.
I get this error:
Person is not abstract and does not override method compare(java.lang.Object, java.lang.Object) in Comparator
public class Person implements Comparator
{
//some methods
public int compare(Person p1, Person p2)
{
// if last names are the same compare first names
if(p1.getLastName().equals(p2.getLastName()))
{
return p1.getFirstName().compareTo(p2.getFirstName());
}
return p1.getLastName().compareTo(p2.getLastName());
}
My child class looks some thing like this:
public class Player extends Person implements Comparator
{
//some methods
public int compare(Player p1, Player p2)
{
if(p1.getGamesPlayed()<p2.getGamesPlayed())
{
return -1;
}else if (p1.getGamesPlayed()==p2.getGamesPlayed())
{
return 0;
}else
{
return 1;
}
}
I also have a club class that stores all info in an ArrayList<Player>
team.
my interface :
public interface Comparator<T>
{
int compare(T o1, T o2);
}
and I also have this class
public class ComparePlayers implements Comparator<Player>
{
public int compare(Player p1, Player p2)
{
if(p1.getGamesPlayed()< p2.getGamesPlayed())
{
return -1;
}else if(p1.getGamesPlayed()== p2.getGamesPlayed())
{
return p1.getLastName().compareTo(p2.getLastName());
}else
{
return 1;
}
}
the spec for this is:
When a new player is signed, she/he should be inserted into the Club class in alphabetical order of last name (and first name if last names are the same). To do this make your Person and Player class implement the appropriate Comparable interface.
Write a class ComparePlayers 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). Implement a new Constructor for the Club class that takes a Comparator<Player>
parameter. Hence write a main program that will print information about each player in the club where players are listed by decreasing order of games played. This should allow ordering to be dictated by the main program without modifying the code in any of your other classes.
I'm sorry if this is long winded but I am struggling to see what is wrong, I have tried several variation and it just wont work. this is due in on Friday, just a push in the right direction would be hugely appreciated.
Change your compare implementation to:
public int compare(Object o1, Object 02)
{
Person p1 = (Person)o1;
Person p2 = (Person)o2;
// if last names are the same compare first names
if(p1.getLastName().equals(p2.getLastName()))
{
return p1.getFirstName().compareTo(p2.getFirstName());
}
return p1.getLastName().compareTo(p2.getLastName());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With