java中如何实现比较器?

发布于 2024-12-22 21:45:03 字数 564 浏览 2 评论 0原文

Stop(Id, Name) 是一个 java 类,我想将这些停止对象存储在 java.util.Set 中,并且这些对象应根据 < Stop 的 code>Id。 这是我的比较器

public class StopsComparator implements Comparator{

    @Override
    public int compare(Object o1, Object o2) {
        // TODO Auto-generated method stub
        Stop stop1 = (Stop)o1;
        Stop stop2 = (Stop)o2;

        return stop1.getStopId().compareTo(stop2.getStopId());
    }
}


 private Set<Stop> stops = new TreeSet<Stop>(new StopsComparator());

,但它没有给出正确的结果?

Stop(Id, Name) is a java class, and i want to store these stop objects in a java.util.Set and those objects should be sorted according to the Id of Stop.
this is my comparator

public class StopsComparator implements Comparator{

    @Override
    public int compare(Object o1, Object o2) {
        // TODO Auto-generated method stub
        Stop stop1 = (Stop)o1;
        Stop stop2 = (Stop)o2;

        return stop1.getStopId().compareTo(stop2.getStopId());
    }
}


 private Set<Stop> stops = new TreeSet<Stop>(new StopsComparator());

but its not giving correct result?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

归属感 2024-12-29 21:45:03

Stop 是否实现了与比较器在同一字段上工作的 equals 方法?如果不这样做,就会导致问题。您可能还希望切换到让您的对象实现 Comparable (尽管这不能解决您所看到的问题)。

一旦实现了 equals() 方法,您还应该实现适用于同一字段的 hashCode() 方法。

Findbugs 可能会告诉你这些事情。它非常有用。

Does Stop implement an equals method that works on the same field as your comparator? If not then that will lead to problems. You also might want to switch to have your object implement Comparable (although that wouldn't fix the problem you're seeing).

Once you implement an equals() method, then you should also implement a hashCode() method that works on the same field.

Findbugs would have probably told you these things. Its extremely useful.

清风挽心 2024-12-29 21:45:03

以下代码对我有用 -

public class Stop {

    private Long id;
    private String name;

    public Stop(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Stop{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    private static class StopComparator implements Comparator<Stop> {


        public int compare(Stop o1, Stop o2) {
            return o1.getId().compareTo(o2.getId());
        }
    }

    public static void main(String[] args) {
        Set<Stop> set = new TreeSet<Stop>(new StopComparator());
        set.add(new Stop(102L, "name102"));
        set.add(new Stop(66L, "name66"));
        set.add(new Stop(72L, "name72"));
        System.out.println(set);
    }
}

印刷品 -

[停止{id=66, name='name66'}, 停止{id=72, name='name72'}, 停止{id=102,
名称='name102'}]

Ofc 您需要实现 equalshashcode 以便类在每个 Set 实现中表现一致,但对于 TreeSet 这应该按原样工作,因为 TreeSet 在执行 addremove 时依赖于 compareTo 方法或包含操作(而不是像HashSet那样的equals)。

The following code works for me -

public class Stop {

    private Long id;
    private String name;

    public Stop(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Stop{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    private static class StopComparator implements Comparator<Stop> {


        public int compare(Stop o1, Stop o2) {
            return o1.getId().compareTo(o2.getId());
        }
    }

    public static void main(String[] args) {
        Set<Stop> set = new TreeSet<Stop>(new StopComparator());
        set.add(new Stop(102L, "name102"));
        set.add(new Stop(66L, "name66"));
        set.add(new Stop(72L, "name72"));
        System.out.println(set);
    }
}

prints -

[Stop{id=66, name='name66'}, Stop{id=72, name='name72'}, Stop{id=102,
name='name102'}]

Ofc you need to implement equals and hashcode so that class behaves consistently in each Set implementation, but for TreeSet this should work as is since TreeSet relies on compareTo method while performing add, remove or contains operations (instead of equals like HashSet).

卖梦商人 2024-12-29 21:45:03

这是来自 Comparator文档:

当且仅当 c.compare(e1, e2)==0 与 e1.equals(e2) 具有相同的布尔值时,比较器 c 对一组元素 S 施加的排序才被认为与 equals 一致对于 S 中的每个 e1 和 e2。

在使用能够施加与 equals 不一致的排序的比较器来对排序集(或排序映射)进行排序时,应小心谨慎。假设带有显式比较器 c 的排序集(或排序映射)与从集合 S 中提取的元素(或键)一起使用。如果 c 对 S 施加的排序与 equals 不一致,则排序集(或排序映射)将行为“奇怪”。特别是排序集(或排序映射)将违反集合(或映射)的一般契约,该契约是根据 equals 定义的。

我建议尝试实现 equalshashCode

This is from the Comparator docs:

The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S.

Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals.

I would recommend to try implementing equals and hashCode.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文