Reputation: 1720
So I have a setup like this:
interface A{
}
class B implements A{
public int hashCode() {
...
}
public boolean equals(final Object obj) {
...
}
}
class C implements A{
public int hashCode() {
...
}
public boolean equals(final Object obj) {
...
}
}
class D{
List<A> list = new ArrayList<A>();
}
I want to implement an overridden equals
method for class D that tests that the lists are equal, but for some reason whenever I try to implement that as this:
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final D other = (D) obj;
if (values == null) {
if (other.values != null)
return false;
}else if (!values.equals(other.values))
return false;
return true;
}
but I believe that this calls Object
's equals
method where it calls values.equals(other.values)
, because it is not behaving correctly.
What can I do to make D
's equals
method behave correctly?
Upvotes: 0
Views: 125
Reputation: 2803
Indeed, you need to override the equals such that you define a comparison factor between the actual lists.
If you use Maven for dependency management, here you can find Apache Commons Lang3 which contains a handy class called EqualsBuilder, very useful for overriding equals method.
Upvotes: 1
Reputation: 680
equals
method is available from Object
class. So it is available in all the concrete Java Classes. The signature of equals method is public boolean equals(Object equals)
.
Also, equals
method should work in tandem with hashcode
method for checking the equality. Its robust way for confirming.
Upvotes: 0
Reputation: 3343
Your last comparison should use Arrays.equals(list, ((D)other).list)
to compare all array elements. Is VSequence
actually D
? Then you can drop the cast to D
.
Upvotes: 0
Reputation: 1406
equals()
is the predefined method which is belongs to Object
class. Remember java is the Object oriented programming language which means that equals()
method is applicable to every java class implicitely. you have not use the predefined method names as your custom methods.
Inorder to simulatte the equals()
you need to change the signature, like this,
public boolean equals_simulation(final Object obj) {
...
}
Upvotes: 2
Reputation: 1676
If you are using an IDE such as Eclipse and you don't need to implement custom rules for equality, you can have Eclipse implement the method for you. Just look for the "override equals and hashCode" option. It should be under Source, or Source > refactor.
Upvotes: 1