ToopDoop
ToopDoop

Reputation: 11

Creating New Comparator for TreeSet in Java

I have a user-defined class called User. This class implements comparable, and has the data fields ID number, followers, and following.

I want to sort the elements in the TreeSet so that the User with the most followers is first, and the User with the least followers is last. If both Users have the same number of followers, then sort based on how many people the User is following. If they are following the same number of people, then sort based on the ID number.

class User implements Comparable<User>
{
    private int userId;
    private ArrayList<User> following;
    private ArrayList<User> followers;
    Set<User> sortingSet = new TreeSet<User>();
}

I've also implemented a compareTo method

public int compareTo(User other)
{
    if(this.followers.size() > other.followers.size())
        return -1;

    if(this.followers.size() < other.followers.size())
        return 1;

    if(this.following.size() > other.following.size())
        return -1;

    if(this.following.size() < other.following.size())
        return 1;

    if(this.userId < other.userId)
        return -1;

    if(this.userId > other.userId)
        return 1;

    return 0;
}

When I add to the TreeSet, it just sorts based on userId.

EDIT: Thanks for the help, I've made some changes to the code so far. I've removed some superfluous if statements. I've also implemented the compareTo method, but the problem still remains the same. I have also already written equals() and hashcode() methods.

EDIT2: Once again, thanks for the help everybody. I've figured out the problem, and it's related to how I initialized the followers and following ArrayLists. I'm blaming that mistake on my lack of sleep.

Upvotes: 0

Views: 108

Answers (1)

Michael
Michael

Reputation: 44150

You have not created a comparator. You have created a thing called Comp which can be compared to users.

A comparator is a thing which compares two things. Comparable is something which can compare itself to something.

Comparable.compareTo takes one argument. Comparator.compare takes two arguments.

Upvotes: 1

Related Questions