Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Predicate<T> method equals()

Tags:

java

guava

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,

like image 891
Ricky Bobby Avatar asked Dec 10 '22 08:12

Ricky Bobby


2 Answers

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.

like image 91
Jon Skeet Avatar answered Dec 11 '22 23:12

Jon Skeet


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);
}
like image 21
Ray Avatar answered Dec 11 '22 23:12

Ray