Java Reference
In-Depth Information
object, and the equals method uses your own business logic to determine if two objects are
equal. To refresh your memory, see if you can determine the output of the following:
4. String x = “hi”;
5. String y = new String(“hi”);
6. if(x == y) {
7. System.out.println(“x == y”);
8. }
9. if(x.equals(y)) {
10. System.out.println(“x.equals(y)”);
11. }
Because x and y point to different objects, line 6 is false . Because the two objects are
equal in the sense of String equality, line 9 is true . Therefore, the output of the previous
code is
x.equals(y)
The equals method plays an important role in the Java Collections Framework. Sets do
not allow duplicate elements and maps do not allow duplicate keys. The set and map classes
use the equals method of the objects in the collection to determine if two objects are equal.
If you are using collections, you should include an equals method in your classes. When
overriding equals , be sure to override hashCode so that two equal objects generate the same
hashCode , as demonstrated by the following Product class:
public class Product {
String description;
double price;
int id;
public boolean equals(Object obj) {
if(!(obj instanceof Product)) {
return false;
}
Product other = (Product) obj;
return this.id == other.id;
}
public int hashCode() {
return id;
}
}
Search WWH ::




Custom Search