简体   繁体   English

java独特元素的集合

[英]java collection of unique elements

I have a Collection coll of myObject. 我有一个myObject的Collection coll。 I'd like to add an element to coll only if there is no such element in the collection. 只有在集合中没有这样的元素时,我才想添加一个元素。

I have overriden the equals method of myObject. 我已经覆盖了myObject的equals方法。 It checks for the equality of its 20 attributes. 它检查其20个属性的相等性。

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. 但是在集合的情况下,我想基于这些属性中的一个来进行相等性检查(以及因此添加)。

Maybe my architecture is flawed, and I shouldn't have two definitions of equals, and should instead have 2 different objects. 也许我的架构是有缺陷的,我不应该有两个equals的定义,而应该有两个不同的对象。

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. 也就是说,我想要某种Set集合,在那里我可以告诉如何进行比较检查。 This would be similar to the Collection.sort() method, where you can provide the comparator to check for the comparison. 这与Collection.sort()方法类似,您可以在其中提供比较器以检查比较。

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

您正在寻找Set和其中一个实现。

You cannot use the existing containers to enforce uniqueness here, because they all want to use equals . 您不能使用现有容器来强制执行唯一性,因为它们都希望使用equals

If it is only one attribute, you could use a Map, with that attribute as a key. 如果它只是一个属性,则可以使用Map,将该属性作为键。 That will allow only one entry per value for that attribute. 这将允许该属性的每个值只有一个条目。

equals and hashCode are intended to be used with Collections. equalshashCode旨在与集合一起使用。 You should change your design. 你应该改变你的设计。 Maybe call your own equals (the one you have now) something else. 也许打电话给你自己的平等(你现在拥有的)别的东西。 Maybe don't put these things into collections directly, but wrapped into an adapter of some sort. 也许不要将这些东西直接放入集合中,而是包装到某种适配器中。

By using a TreeSet(Comparator comparator) you don't need to rely on the 'equals/hashCode' implementation. 通过使用TreeSet(比较器比较器),您不需要依赖'equals / hashCode'实现。

Similarly if your collection is a list you can sort it using a comparator Collections.sort(List list, Comparator c); 同样,如果您的集合是一个列表,您可以使用比较器Collections.sort(列表列表,比较器c)对其进行排序;

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

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