How to check if 2 Class instances are the same
equals, java
Solution
You should have included your `Fruit` class, but here is one way
static class Fruit {
private String name;
public Fruit(String name) {
this.name = name;
}
@Override
public boolean equals(Object otherObject) {
// check for reference equality.
if (this == otherObject) {
return true;
}
if (otherObject instanceof Fruit) {
Fruit that = (Fruit) otherObject;
// Check for name equality.
return (name == null && that.name == null)
|| name.equals(that.name);
}
return false;
}
}
public static void main(String[] args) {
Fruit apple = new Fruit("apple");
Fruit apple2 = new Fruit("apple");
Fruit orange = new Fruit("orange");
if (apple.equals(orange))
System.out.println("true");
else
System.out.println("false");
// You can also use the shorter
System.out.println(apple.equals(apple2));
}
Outputs
false
true
Problem
For example I have a class Fruit. I create 2 instances: ``` Fruit apple = new Fruit("apple"); Fruit orange = new Fruit("orange"); ``` The value of the 2 instances are not the same thus I am looking for the answer to be false. I override the .equals() method and wrote the following method to do the test: ``` @Override public boolean equals(Object otherObject){ if(otherObject instanceof Fruit){ return true; } return false; } if(apple.equals(orange)) System.out.println("true"); else System.out.println("false"); ``` The above method gives me the answer as true. From my understanding, this is a correct response since this simply tests if they both belongs to the same Class which is true. But I can't get around to testing the values of the instances itself. Please advice. Thanks.