Having Node abstract class which Cell extends him .
In Cell I implemented public boolean equals(Node cmpCell) . I created Set<Node> closeList = new HashSet<Node>(); and when I execute closeList.contains((Cell) node) I debugged it and detect that it utterly ignores Cell equals I implemented . What I did wrong ?
Edit :
I changed in Cell to
#Override
public boolean equals(Object cmpCell)
and still closeList.contains((Cell) node) doesn't using the above override .
2nd Edit :
In Cell class there is 2 members -
int colIndex ;
int rowIndex ;
the equals override just compare them to that both members of the 2nd class , I think it would be better I use HashMap<K, V> but still I would be glade to know how the hashCode should be looks like in such case ?
public boolean equals(Node cmpCell)
This is not a valid override. The syntax of equals method of Object class is: -
public boolean equals(Object)
And yes, as pointed out by #JonSkeet in comment, whenever you are overriding equals method, also remember to override hashCode method to follow the contract of equals and hashCode. Because if you don't do that, then even if your equals method shows evaluates your instances as equal, the default hashCode implementation in Object class will generate different hashCodes for them, and hence they won't be equal.
Also, ensure that, while calculating hashcode, you consider only those attributes, that you used to compare your instances in equals method. Else, again you will get incorrect result.
In addition to that, if you are using any IDE like Eclipse, it generates a very nicely overridden and compatible equals and hashCode method for you. You should be better using them.
You need to right-click on your class, go to source and select Generate equals and hashCode method.
You probably didn't override the hashCode method.
An object in a hashset is found using the hashcode first. You must always override both or none of the two equals and hashCode methods.
Well there are three potential issues:
You overrode the wrong signature. Should be public boolean equals(Object)
If you override equals you must implement hashCode
Is your equals method symmetric (x.equals(y) implies y.equals(x)) and does it play correctly with polymorphism, ie can you have a Node.equals(Cell) but the reverse be false?
As already stated, hashCode and equals must be implemented accordingly.
But the question asked here is "Why isn't the custom equals() called?". So, the answer is, that Java doesn't support multiple dispatch.
Simple example
If you declare Object myCell = new Cell(), then myCell2.equals(myCell) can only determine the declared type of myCell, which is Object.
Your case
The signature of the called methods is: HashSet.contains(Object o), with the same consequences as stated above.
You can do something like that, although it isn't a nice solution:
public class Cell {
#Override
public boolean equals(Object o) {
if(o instanceof Cell) {
// your code
}
super.equals(o);
}
}
Related
I want to use a HashSet to store some objects:
public class StoredObject{
Type type; //Type is an enum
//other fields
Type getType(){return type;}
}
Now, I want to store only one StoredObject of the same Type, so I override contains() in a subclass of HashSet:
public MySet<E extends StoredObject> extends java.util.HashSet<E>{
#Override
public boolean contains(Object o) {
if(StoredObject.class.isAssignableFrom(o.getClass())) {//if o implements StoredObject
for(StoredObject s : this) {
if(s.getType() == ((StoredObject) o).getType()) return true;
}
}
return false
}
}
Before this I wanted to use HashSet and modify the equals() of StoredObject. However, the way above seems like a shorter and safer way, especially as in my case the stored objects all implement an interface and don't extend the same class.
Now my question: Is this implementation safe? I tried to search for things it could break, but did not find any. I read that overriding equals() can break Collections.
Also, does this subclass defeats the purpose of an HashSet, since it does not use the HashMap for contains()?
HashMap<Type,StoredObject> is the appropriate collection for this.
If you override equals(Object) then you must also override hashCode (it's also not a bad idea to make it implement Comparable and perhaps override toString). Use the #Override annotation to ensure you have the right parameter types and spelling - very easy to get wrong and confusing to debug.
What can go wrong?
There's a lot of methods in HashSet to override, so that's a lot of work.
More methods may be added to HashSet in future versions of Java - how are you going to look out for this?
contains should be an O(1) operation (assuming a good distribution of hash codes), but the OP implementation is O(n).
Set.equals on another Set will report incorrect results.
Note also that StoredObject.class.isAssignableFrom(o.getClass()) is better written as o instanceof StoredObject (assuming you've got isAssignableFrom the right way around).
Is this implementation safe?
Absolutely not. There are other methods on HashSet that wouldn't work correctly, e.g. add(), leaving the size of the set incorrect.
Besides, that implementation would totally ruin the performance of the contains method, making it run in O(n) instead of O(1).
If you need a Set with a definition of equality that differs from the objects natural definition as implemented by equals() and hashCode(), use a TreeSet and supply a custom Comparator.
class MySet<E extends StoredObject> extends java.util.TreeSet<E> {
public MySet() {
super(Comparator.comparing(StoredObject::getType));
}
}
I do agree with Tom Hawtin - tackline, that HashMap<Type, StoredObject> is a better option, because it allows you to get the StoredObject for a given Type, which is otherwise very difficult to do with a Set. It also allows you to check for existence given just a Type, without having to create a dummy StoredObject object for the check.
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.
I don't understand something silly in Java and was hoping you could clear it up for me.
I have defined Hashset<Point> myHashSet = new HashSet<Point>();
Then, I create two equal Point points, Point p1 and Point p2, and put them in different variables/memory locations. Then I override the .equals() method for public boolean equals(Point other) and added my first point, p1, to the HashSet.
Then I call System.out.println(myHashSet.contains(p2)); // prints false
Why can the compiler not infer "Oh, this hashset is of type Point" from the when it is being created and say "I should check to see if Point has overridden the default equals method...yup, let's call that one!".
Instead, I believe it calls the generic equals method for objects, thus comparing memory location, I believe ?
Is the reasoning for this simply that the HashSet could contain a subclass of Point which uses a different Equals method ? This is the only reason I can see for the current behaviour, though I am sure I am overlooking something :). Thanks a lot.
Collections use Object.equals(Object) which you have to override. If you create another method like equals(Point) it won't call it.
Instead, I believe it calls the generic equals method for objects, thus comparing memory location, I believe ?
Yes, as the only method which HashSet can generically call is equals(Object)
Is the reasoning for this simply that the HashSet could contain a subclass of Point which uses a different Equals method ?
The HashSet has no way of know that you want to use this method instead at runtime.
You should override both equals() and hashCode() according to this doc http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#hashCode%28%29, since HashSet use both of these methods to check if objects are equal
Your problem lies in public boolean equals(Point other), because that is NOT the default equals method defined in the Object class.
You must override public boolean equals(Object other) (notice Object instead of Point) if you wish the HashMap to use your implementation. See the the documentation for Object and note also that if you override equals you SHOULD also override the hashCode() method.
Try adding #Override annotation. You must have misspelled equals method and its signature.
#Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
If I implement equals() and hashCode() in both the parent and child classes, is it necessary to call super.equals() in equals() in the child class, e.g.
public boolean equals(Object obj) {
if (obj.getClass() != ChildClass.class) {
return false;
}
return super.equals() && this.var == ((ChildClass) obj).var;
}
I am assuming that the parent class is not Object and is giving the correct definition of equals and hashCode.
No, that's not necessary, and would probably be wrong. Indeed, part of the reason why you're overriding equal is because super.equals doesn't give the correct behaviour (right?).
Or put another way, if super.equals gives the correct behaviour, you probably don't need to go to the trouble of overriding it.
But if you are overriding equals, then yes, you need to override hashCode, too.
If your super class doesn't implement equals, then calling super.equals will get you the Object implementation which only compares references, so in any normal equals implementation where you want to compare a business key it would actually cause a lot of false negatives.
That said, your implementation above really isn't any different semantically than the default equals implementation in Object since you are just using == for comparison.
As for hashCode, if you override equals you really should override hashCode in order to keep the contract of the two. For instance, if you are using a business key for equals you should probably use the same business key for the hashcode so that two objects that are equal generate the same hashcode.
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)