Java中的深度比较集 [英] Deep compare sets in Java

查看:163
本文介绍了Java中的深度比较集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有两个比较 Item 对象的集合。有没有一种比较集合的方法,以便调用 Item 等于方法而不只是比较引用?

解决方案

AbstractSet 的每个孩子都这样做。请参阅文档


public boolean equals(Object o)



将指定对象与此集进行相等性比较。如果给定对象也是一个集合,则返回true,两个集合具有相同的大小,并且给定集合的每个成员都包含在此集合中。这可确保equals方法在Set接口的不同实现中正常工作。
此实现首先检查指定的对象是否为此set;如果是这样,它返回true。然后,它检查指定的对象是否是一个大小与该集合的大小相同的集合;如果不是,则返回false。如果是这样,它返回containsAll((Collection)o)。


所以实际上这依赖于包含实现(由 containsAll(..)调用)。对于 HashSet (至少)这就是你要找的。

I have two sets in Java that compare Item objects. Is there a method to compare the sets so that Item's equals method is invoked and not just compare references?

解决方案

Each child of AbstractSet does that. See the docs

public boolean equals(Object o)

Compares the specified object with this set for equality. Returns true if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface. This implementation first checks if the specified object is this set; if so it returns true. Then, it checks if the specified object is a set whose size is identical to the size of this set; if not, it returns false. If so, it returns containsAll((Collection) o).

So in fact this relies on the contains implementation (which is invoked by containsAll(..)). For HashSet (at least) this is what you are looking for.

这篇关于Java中的深度比较集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆