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,
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
and PredicateM
are different references, equals
returns false.
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 make predicateD
and predicateM
instances of that class. Then your equals method might look like:
public boolean equals(Object o) {
if (o instanceof IntegerCheckPredicate) {
return true;
}
return false;
}
Then this test would pass:
@Test
public void testPredicatesWithEqualsOverriddenAreEqual() {
IntegerCheckPredicate predicateM = new IntegerCheckPredicate();
IntegerCheckPredicate predicateD = new IntegerCheckPredicate();
assertEquals(predicateM, predicateD);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With