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?
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.
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.
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.
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()
.
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.
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