Why was the equals() method in java.util.Comparator made abstract, if it is already implemented in the Object class?
First of all, it's worth noting that the method is not "made abstract". If you implement Comparator<T> without implementing equals(), your code will compile. Your class will simply use the implementation provided by Object.
As to why re-declare the method, this is done because the contract on Comparator<T>.equals() is more stringent than the contract on Object.equals(). This is explained in the documentation:
Additionally, this method can return true only if the specified object is also a comparator and it imposes the same ordering as this comparator. Thus, comp1.equals(comp2) implies that sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2)) for every object reference o1 and o2.
If Comparator did not override equals(), there would be no good way to specify that its contract on equals() is different from Object's.
Related
Is a new implementation of the hashcode() method required when we override the equals() method from the superclass. The contract between equals() and hashcode() is kept.
The equals and hashCode methods will be (just like any other method) inherited from the superclass.
If those are still appropriate for the subclass you can keep this as is.
There are examples in the JDK for this:
Stack extends Vector extends AbstractList
Stack just inherits equals from Vector
Vector overrides equals from AbstractList, but only to add synchronized and then just calls super.equals.
ArrayList also extends AbstractList, but it overrides equals with an implementation that follows the same logic, but can be more efficient because it knows that at least one of the participants is an ArrayList.
But keep in mind that
you will now be comparing Super <-> Super, Super <-> Sub, Sub <-> Sub instances in all combinations with the same piece of code
things like this.getClass() might return unexpected things when this can actually be a subclass
If that causes problems in your comparison logic is up to you to decide.
Contract between equals and hashcode method need to be kept when your are going to use that class in hashing based collections, like hashmap, hashset etc which uses hashcode method to calculate the hash index and equals method to check the equality. Otherwise you can ignore hashcode. Please refer below URL for more information on equals and hashcode method overriding in hashmap.
https://www.thetechnojournals.com/2019/10/why-hashmap-key-should-be-immutable-in.html
I understand the purpose of making the clone and finalize method as protected, I wanted to understand why hashcode() and equals method are not declared as protected
Because you want to call hashcode and equals methods from the outside of that given class.
protected allows access only from the same package and extending classes.
You "understand the purpose of making the clone and finalize method as protected". But what is the purpose actually?
Calling Object.clone will throw an exception if the method isn't overridden and if Cloneable isn't implemented. Thus this method isn't ready to use.
Object.finalize is according to JavaDoc "called by the garbage collector". Thus it is for internal usage only.
In contrast to these both methods are Object.equals and Object.hashCode ready to use and not for internal usage.
The JavaDoc of Object.hashCode says:
This method is supported for the benefit of hash tables such as those
provided by HashMap.
Thus it is intended to be used by other objects. If hashCode wouldn't be declared public this functionality would be limited usable.
Object.equals is a symmetric method. If Object.equals wouldn't be declared public, suppose we have a local variable b of a type from another package and whose equals method isn't visible to this. We want to ckeck if b and this are equal. We couldn't call b != null && b.equals(this) but we could still call this.equals(b). Does it makes sense to limit a symmetric method to be callable by one of both objects only?
See also Comparable.
Say I have class A, which override the default equals method and implement Comparable interface (Comparable interface is said to be the natural ordering). To conform to good practice, the result returned by equals and Comparable's compareTo method should be consistent.
On some occasions, I want to compare instance of class A differently, so I implement Comparator interface (Comparator interface is said to be the unnatural ordering). So using Comparable's compareTo method and Comparator's compare method, the result would not be consistent.
If equals method and Comparable's compareTo interface is consistent, Comparable's comparaTo method and Comparator's compare method is not consistent, then equals method and Comparator's compare method would not be consistent as well.
So what are the consequences of equals method not consistent with Comparator's compare method, if there is any?
Wondering what needs to be done for listed method
public final int compareTo(final FieldDTO o) {
return o.available.compareTo(this.available);
its throwing exception on line 2 stating
Bad practice - Class defines compareTo(...) and uses Object.equals() 16 days
field defines compareTo(FieldDTO) and uses Object.equals()
Not sure how should i handle this.
Thanks in advance.
If you define compareTo you should at least define equals
boolean equals(it) {
return compareTo(it) == 0;
}
otherwise you will get strange problems when you put your object in Maps and Sets. It is generally good practice to also define hashCode.
you need to override Object class equals() and hashCode() methods.
Use IDE generated code for these, it will pull all the Object attributes and creates method for you.
On eclipse IDE:
Right click on the class
Select Source
Generate hashCode() and equals()...
This is the documentation from FindBugs:
Eq: Class defines compareTo(...) and uses Object.equals()
(EQ_COMPARETO_USE_OBJECT_EQUALS)
This class defines a compareTo(...) method but inherits its equals()
method from java.lang.Object. Generally, the value of compareTo should
return zero if and only if equals returns true. If this is violated,
weird and unpredictable failures will occur in classes such as
PriorityQueue. In Java 5 the PriorityQueue.remove method uses the
compareTo method, while in Java 6 it uses the equals method.
From the JavaDoc for the compareTo method in the Comparable interface:
It is strongly recommended, but not strictly required that
(x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class
that implements the Comparable interface and violates this condition
should clearly indicate this fact. The recommended language is "Note:
this class has a natural ordering that is inconsistent with equals."
So it seems you need to implement the equals method thus overriding the default implementation from Object.
Say I have my own class
public class MyObj { /* ... */ }
It has some attributes and methods. It DOES NOT implement equals, DOES NOT implement hashCode.
Once we call equals and hashCode, what are the default implementations? From Object class? And what are they? How the default equals will work? How the default hashCode will work and what will return? == will just check if they reference to the same object, so it's easy, but what about equals() and hashCode() methods?
Yes, the default implementation is Object's (generally speaking; if you inherit from a class that redefined equals and/or hashCode, then you'll use that implementation instead).
From the documentation:
equals
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns
true if and only if x and y refer to the same object (x == y has the value true).
hashCode
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
From Object in one of the JVM implementations:
public boolean equals(Object object) {
return this == object;
}
public int hashCode() {
return VMMemoryManager.getIdentityHashCode(this);
}
In both cases it's just comparing the memory addresses of the objects in question.
There are default implementations of equals() and hashCode() in Object. If you don't provide your own implementation, those will be used. For equals(), this means an == comparison: the objects will only be equal if they are exactly the same object. For hashCode(), the Javadoc has a good explanation.
For more information, see Effective Java, Chapter 3 (pdf), item 8.
Yes, from Object class since your class extends Object implicitly. equals simply returns this == obj. hashCode implementation is native. Just a guess - it returns the pointer to the object.
If you do not provide your own implementation, one derived from Object would be used. It is OK, unless you plan to put your class instances into i.e. HashSet (any collection that actually use hashCode() ), or something that need to check object's equality (i.e. HashSet's contains() method). Otherwise it will work incorrectly, if that's what you are asking for.
It is quite easy to provide your own implementation of these methods thanks to HashCodeBuilder and EqualsBuilder from Apache Commons Lang.
IBM's developerworks says:
Under this default implementation, two
references are equal only if they
refer to the exact same object.
Similarly, the default implementation
of hashCode() provided by Object is
derived by mapping the memory address
of the object to an integer value.
However, to be sure of the exact implementation details for a particular vendor's Java version it's probably best to look as the source (if it's available)