有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何为集合正确编写此比较器。排序(arrayList、comparator)?

我写了一个比较器来比较两个物体

希望每个对象的方法都是不言自明的。当我将我的ArrayList放入Collections.sort(arrayList, comparator)时,它根本不会排序

public int compare(User o1, User o2) {
final int followersComparison = Integer.compare(o2.getWhoThisUserIsBeingFollowedBy().size(), o1.getWhoThisUserIsBeingFollowedBy().size());

if (followersComparison != 0) {
  return followersComparison;
}

final int followingComparison = Integer.compare(o2.getWhoThisUserIsFollowing().size(), o1.getWhoThisUserIsFollowing().size());

if (followingComparison != 0) {
  return followingComparison;
}

// Note here o1 and o2 is in opposite order than above
return  Integer.compare(o1.getUserId(), o2.getUserId());

}

我希望Collections.sort能根据这个比较器对我的ArrayList进行排序,但它没有


共 (1) 个答案

  1. # 1 楼答案

    这是怎么回事:

    public int compare(User o1, User o2) {
        final int followersComparison = Integer.compare(o2.getWhoThisUserIsBeingFollowedBy().size(), o1.getWhoThisUserIsBeingFollowedBy().size());
    
        if (followersComparison != 0) {
          return followersComparison;
        }
    
        final int followingComparison = Integer.compare(o2.getWhoThisUserIsFollowing().size(), o1.getWhoThisUserIsFollowing().size());
    
        if (followingComparison != 0) {
          return followingComparison;
        }
    
        // Note here o1 and o2 is in opposite order than above
        return  Integer.compare(o1.getUserId(), o2.getUserId());
    
      }
    

    似乎在比较数字时,您可能遗漏了其他一些部分(例如,如果o1.getwhoThisUserIsBeingFollowedBy().size() > 02.getwhoThisUserIsBeingFollowedBy().size()只返回1,但如果是相反的情况,该怎么办)。我倾向于犯同样的错误,这就是为什么我更喜欢使用整数。比较