简体   繁体   中英

Java, how to sort an list of Nodes by an objects field

I made an class called myLinkedList that stores nodes from a class called LinkNodes that takes an object with an name(String), as a field. I want to sort the nodes in my list alphabetical, from the memberPlayer field firstName

public class LinkNode {
    public memberPlayer player;
    public LinkNode next;

    public LinkNode() {
        this(null, null);
    }
    public LinkNode(memberPlayer player) {
        this(player,null);
    }
    public LinkNode(memberPlayer player, LinkNode next) {
        this.player = player;
        this.next = next;
    }
    public String toString() {
        String result = player + " ";
        if (next != null) {
            result += next.toString();
        }
        return result;
    }
}

I have tried with the collection.sort method but, without luck, as i tried to use it on an list that i created myself, but it worked fine, when i just used the objects. Is there somehow special i need to do, if I want to acces the field of an object inside a node?

memberPlayer class:

public class memberPlayer implements Comparable<memberPlayer>{
    private String firstName;
    private String lastName;
    private int age;
    private String team;
}

You should implement the compareTo method in the Comparable interface to use a specific field.

 @Override 
 public int compareTo(Object o) {
   MemberPlayer player = (MemberPlayer)o;
   return this.firstName.compareTo(player.firstName);
 }

P:S Always use proper conventions when naming classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM