public class Foo{
private final int A;
private final int B;
public boolean equals(Object o){
//type check omitted
return A==o.A && B==o.B;
}
}
我想要另一个像这样的.equals()
方法
public boolean equals(Object o){
return A==o.A;
}
Foo对象首先是用A,B字段创建的,然后我想将它们发送到一个Set<E>
,该方法使用第二个equals()方法对只比较字段A。
我知道我可以创建只有一个字段的新对象,但是开销会很大。有什么建议吗?
发布于 2011-06-16 20:38:02
使用组合,您可以创建一个FooWrapper
类,该类提供equals
的自定义实现,并将其添加到集合中:
public class FooWrapper {
public final Foo foo; //constructor omitted
public boolean equals(Object other) {
//type check omitted here too
return foo.A == other.foo.A;
}
//hashCode omitted, but you need that too
}
不幸的是,使用Java,除了上面的方法或子类以及重写equals
之外,没有办法告诉集合使用自定义的equals()
计算。
编辑:
我觉得您可能会转而使用Map<Integer, Foo>
,使用foo.A
作为键,使用foo
作为值(从而将其限制为A
的唯一值)。不过,如果没有更多的背景,我无法告诉你这样做是否合适。
发布于 2011-06-16 20:39:47
每个Object
只能有一个等于的实现,因为它正在覆盖从java.lang.Object
继承的方法。我认为您需要决定平等对于Foo
意味着什么--A是唯一重要的字段;如果是的话,就使用它吧。您的替代方法是包装Foo
并为WrappedFoo
对象提供自定义equals
方法。然后可以将WrappedFoo
存储在Set
中。
从设计的角度看,这里应该有两个对象--一个是A的值类,另一个是B的值类。如果需要一个对象来表示A和B,就可以使用组合。
发布于 2011-06-16 20:42:16
为此,我编写了一个匹配框架:
基本接口是Matcher (类似于可比较的):http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/util/Matcher.html
MatchableObject是一个类,它将匹配策略应用于对象:http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/util/MatchableObject.html
Matcher是一个实用程序类,用于包装/解包装MatchableObjects:http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/util/Matchers.html
图书馆是开源的。也许你觉得它很有用。
首页:
http://www.softsmithy.org
下载:
http://sourceforge.net/projects/softsmithy/files/softsmithy/
Maven:
<dependency>
<groupid>org.softsmithy.lib</groupid>
<artifactid>lib-core</artifactid>
<version>0.1</version>
</dependency>
https://stackoverflow.com/questions/6378232
复制相似问题