[英]java.util.Set, but with custom constraint on field
I wonder if there is a nice way to have Set on objects, but constrained on custom fields. 我想知道是否有一种在对象上设置Set的好方法,但是在自定义字段上有约束。
For example I need a Set
of POJO's: 例如,我需要一Set
POJO:
class MyPojo {
private String name;
private Map<Object, Object> stuff;
//getters, setters, constructor
}
And I want to have a Set
where they will be unique by name. 我想要一个Set
,它们在名称上将是唯一的。 I could implement hash
and equals
based on name
property, but then I can't use really equals
to compare them. 我可以基于name
属性实现hash
和equals
,但是我不能使用真正的equals
来比较它们。
Is there some nice workaround or maybe Guava/apache commons collection for this? 是否有一些不错的解决方法,或者为此提供番石榴/ Apache Commons集合?
You can create wrapper objects. 您可以创建包装对象。 It's like a decorator pattern. 这就像一个装饰器模式。 You wrap your original object with different hash implementations and then wrapped object will be used in the Set. 您用不同的哈希实现包装原始对象,然后包装的对象将在Set中使用。
You can use a HashMap<String,MyPojo>
instead of a Set<MyPojo>
. 您可以使用HashMap<String,MyPojo>
代替Set<MyPojo>
。 This way, each name
can appear at most once in the Map
. 这样,每个name
最多只能在Map
出现一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.