谓词方法等于()
我正在使用来自 com.google.common.base
(Google Guava) 的接口 Predicate
但我不知道如何让 等于()
方法有效...
为什么当我输入这样的内容时会得到 false
:
Predicate<Object> PredicateD = new Predicate<Object>(){
@Override public boolean apply(Object number) {
return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
}
};
Predicate<Object> PredicateM = new Predicate<Object>(){
@Override public boolean apply(Object number) {
return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
}
};
System.out.println(PredicateD.equals(PredicateM));
提前感谢您的帮助,
I'm using the interface Predicate<T>
from com.google.common.base
(Google Guava)
But I don't know how to have the equals()
method works...
Why do I get false
when I type something like this :
Predicate<Object> PredicateD = new Predicate<Object>(){
@Override public boolean apply(Object number) {
return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
}
};
Predicate<Object> PredicateM = new Predicate<Object>(){
@Override public boolean apply(Object number) {
return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
}
};
System.out.println(PredicateD.equals(PredicateM));
Thanks in advance for your Help,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在创建两个不同的匿名内部类,但它们都没有重写
equals
,因此您将获得默认实现,其中任何两个不相等的引用都会被考虑不相等。由于
PredicateD
和PredicateM
的值是不同的引用,因此equals
返回 false。You're creating two different anonymous inner classes, but neither of them is overriding
equals
, so you'll get the default implementation, whereby any two non-equal references are considered non-equal.As the values of
PredicateD
andPredicateM
are different references,equals
returns false.为了让它打印
true
,您必须重写这些类上的 equals 方法。您的自定义 equals 必须检查参数是否是这些类中任一类的实例。由于它们是匿名的,因此您无法引用它们,因此您无法真正做到这一点。我的建议是创建一个非匿名类(例如,
IntegerCheckingPredicate
),并创建该类的predicateD
和predicateM
实例。那么你的 equals 方法可能看起来像:那么这个测试就会通过:
In order to get this to print
true
, you would have to override the equals method on these classes. Your custom equals would have to check if the parameter is an instance of either of these classes. Since they are anonymous, you'd have no way of referencing them, so you can't really do that.My suggestion would be to make a non-anonymous class (say,
IntegerCheckingPredicate
), and makepredicateD
andpredicateM
instances of that class. Then your equals method might look like:Then this test would pass:
我认为没有必要重写 equals()。谓词是函数类。
Object.equals(){return (this == obj);}
是合理的。I don't think it's necessary to override equals(). Predicate is functional class. The
Object.equals(){return (this == obj);}
is reasonable.