Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implement 2 flavors of Equals method for a class in Java

Tags:

java

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;
    }

}

I want to have another .equals() method like this

public boolean equals(Object o){
    return A==o.A;
}

The Foo object is first created with A,B field, then I want to send them off to a Set<E> that used the 2nd equals() method to only compares field A.

I know I can create new objects that only have A field, but overhead would be big. Any advice?

like image 915
Wei Shi Avatar asked Jun 16 '11 20:06

Wei Shi


People also ask

What is equals () method in Java?

Java String equals() Method The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.

What is the default implementation of equals method in object class Java?

Shallow comparison: The default implementation of equals method is defined in Java. lang. Object class which simply checks if two Object references (say x and y) refer to the same Object. i.e. It checks if x == y.

What is equals () method and ==?

In java both == and equals() method is used to check the equality of two variables or objects. == is a relational operator which checks if the values of two operands are equal or not, if yes then condition becomes true. equals() is a method available in Object class and is used to compare objects for equality.


1 Answers

Using composition, you could create a FooWrapper class that provides a custom implementation of equals and add that to the set instead:

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
}

Unfortunately with the Java Collections API there is no way to tell a collection to use a custom equals computation other than the method above or subclassing and overriding equals().

Edit:

It strikes me that you might instead be able to make use of a Map<Integer, Foo> instead, using foo.A as the key and foo as the value (and thus restricting it to unique values of A). I couldn't tell you whether that's suitable without more context though.

like image 83
Mark Peters Avatar answered Nov 20 '22 12:11

Mark Peters