java独特元素的集合 [英] java collection of unique elements

查看:142
本文介绍了java独特元素的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个myObject的Collection coll。我只想在集合中没有这样的元素的情况下添加一个元素。

I have a Collection coll of myObject. I'd like to add an element to coll only if there is no such element in the collection.

我已经覆盖了myObject的equals方法。它检查其20个属性的相等性。

I have overriden the equals method of myObject. It checks for the equality of its 20 attributes.

但是在集合的情况下,我想仅基于等式检查(因此添加)其中一个属性。

However in the case of the collection, I'd like to make the equality check (and hence the add) based only on one of these attributes.

也许我的架构存在缺陷,我不应该有两个equals的定义,而应该有两个不同的对象。

Maybe my architecture is flawed, and I shouldn't have two definitions of equals, and should instead have 2 different objects.

然而,如果没有太多的重构,是否有可能从这里实现我想要的东西?也就是说,我想要一些Set集合,在那里我可以告诉如何进行比较检查。这与Collection.sort()方法类似,您可以在其中提供比较器以检查比较。

However, is it possible, without too much refactoring, to achieve what I want from here ? That is to say, I'd like some sort of a Set collection, where I could tell how to make the comparison check. This would be similar to the Collection.sort() method, where you can provide the comparator to check for the comparison.

推荐答案

转到 HashSet 。它将存储唯一的这里的注释,你必须覆盖hashcode和equals方法,以提供每个对象的唯一性。你可以读取这两种方法之间的关系这里

go for HashSet.It will store unique values.As from comments here, you have to override the hashcode and equals methods to provide uniqueness of every object.You can read relation between these two methods here.

这篇关于java独特元素的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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