简体   繁体   English

在Java中为TreeSet创建新的比较器

[英]Creating New Comparator for TreeSet in Java

I have a user-defined class called User. 我有一个名为User的用户定义类。 This class implements comparable, and has the data fields ID number, followers, and following. 此类实现可比较的类,并具有数据字段ID号,关注者和关注者。

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. 我想对TreeSet中的元素进行排序,以使关注者最多的用户排在第一位,关注者最少的用户排在最后。 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. 如果他们跟随的人数相同,则根据ID号进行排序。

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 我还实现了compareTo方法

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. 当我添加到TreeSet时,它只是基于userId进行排序。

EDIT: Thanks for the help, I've made some changes to the code so far. 编辑:感谢您的帮助,到目前为止,我已经对代码进行了一些更改。 I've removed some superfluous if statements. 我删除了一些多余的if语句。 I've also implemented the compareTo method, but the problem still remains the same. 我还实现了compareTo方法,但问题仍然存在。 I have also already written equals() and hashcode() methods. 我已经写过equals()和hashcode()方法。

EDIT2: Once again, thanks for the help everybody. EDIT2:再次感谢大家的帮助。 I've figured out the problem, and it's related to how I initialized the followers and following ArrayLists. 我已经解决了这个问题,这与初始化跟随者和跟随ArrayLists的方式有关。 I'm blaming that mistake on my lack of sleep. 我将此失误归咎于我的睡眠不足。

You have not created a comparator. 您尚未创建比较器。 You have created a thing called Comp which can be compared to users . 您已经创建了一个称为Comp的东西, 可以与用户进行比较

A compar ator is a thing which compares two things . 比较比较两件东西的东西 Compar able is something which can compare itself to something. 比较能力是可以将自己与事物进行比较的事物。

Comparable.compareTo takes one argument. Comparable.compareTo接受一个参数。 Comparator.compare takes two arguments. Comparator.compare具有两个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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