Im trying to figure out how to sort an ArrayList using comparable, my code looks like this:
public class playerComparsion{
public static void main(String[] args){
ArrayList<Object> list = new ArrayList<Object>();
Player p1 = new Players(1,92,Zlatan);
Player p2 = new Players(2,92,Hazard);
Player p3 = new Players(1,82,Klose);
list.add(p1);
list.add(p2);
list.add(p3);
}
}
class Players implements Comparable{
int position;
String name;
int rating;
public Players(int i, int j, String string) {
this.position=i;
this.rating=j;
this.name=string;
}
public void getRating() {
System.out.println(this.rating);
}
public void getPos() {
System.out.println(this.position);
}
public void getName() {
System.out.println(this.name);
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
}
I want to sort the Arraylist based on the attribute rating. I suppose I should use the compareTo function but I have no idea how, can someone help me?
Don't use a raw type with
Comparable
. Instead, useComparable<Players>
. This way, you have direct access to the object you care about without having to cast fromObject
.The sample
compareTo
would be this:Then, you would actually have to...sort it, using
Collections.sort()
.The reason for
Comparable<Players>
is thatComparable
itself is defined as taking a generic typeT
.Try this.
Instead of making
Player
implementComparable
, you get more flexibility by implementingComparator<Player>
classes. For example:After all,
Player
has multiple fields, it's easy to imagine that sometimes you might want to order players differently. A great advantage of this approach is the single responsibility principle: aPlayer
class does only one thing, encapsulates player data. Instead of adding one more responsibility (sorting), it's better to move that logic in another class.You could use these comparators with
Collections.sort
, for example:Extra tips
Your class seems to be named
Players
. It's better to rename toPlayer
.The
getName
,getRating
,getPos
methods should not returnvoid
and print the result, but return the field values instead.Use better names for the constructor arguments, for example:
Use the right type of list to store players:
Please format your code properly. Any IDE can do that.
Suggested implementation