28

This seems like a silly question but why do we override equals method instead of creating a new method with new name and compare using it?

If I didn't override equals that means both == and equals check whether both references are pointed to same memory location?

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 6
    What about Data structures which use the *available* `equals()` method?. Example Map, Set? – TheLostMind Jan 21 '15 at 10:22
  • 13
    You can also implement `toString()` with a different name. But then no other code (except your own) is going to make use of it. – Thilo Jan 21 '15 at 10:23
  • 7
    BTW, I don't think it's a silly question. I think it's important to understanding the Java object model. – Michael Lorton Jan 22 '15 at 04:16

7 Answers7

57

This seems like a silly question but why do we override equals method instead of creating a new method with new name and compare using it?

Because all standard collections (ArrayList, LinkedList, HashSet, HashMap, ...) use equals when deciding if two objects are equal.

If you invent a new method these collections wouldn't know about it and not work as intended.

The following is very important to understand: If a collection such as ArrayList calls Object.equals this call will, in runtime, resolve to the overridden method. So even though you invent classes that the collections are not aware of, they can still invoke methods, such as equals, on those classes.

If I didn't override equals that means both == and equals check whether both references are pointed to same memory location?

Yes. The implementation of Object.equals just performs a == check.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • One last thing. If i made two Strings like this //String a = "Hello"; String b = "Hello"; that means both a and b references are pointed to the same object? So i can use equals() to compare them anytime without overriding it? – Lakshitha Ranasinghe Jan 21 '15 at 11:05
  • [Strings are special](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) in Java. If you do `String a = "Hello"; String b = "Hello";` then `== ` will work. – aioobe Jan 21 '15 at 11:11
  • Got it, that is why == can not be used to compare two String contents :) – Lakshitha Ranasinghe Jan 21 '15 at 11:12
  • 6
    Right. In general you can't use == when comparing Strings :-) (It *might* work if you have compile time constants.) In general Strings are bad to use as example when explaining / thinking about equals vs ==. – aioobe Jan 21 '15 at 11:12
9

You override equals if you are using classes that rely on equals, such as HashMap, HashSet, ArrayList etc...

For example, if you store elements of your class in a HashSet, you must override hashCode and equals if you want the uniqueness of elements to be determined not by simple reference equality.

Yes, if you don't override equals, the default equals implementation (as implemented in the Object class) is the same as ==.

Eran
  • 387,369
  • 54
  • 702
  • 768
5

In addition to the main reason, already given in other answers, consider program readability.

If you override equals and hashCode anyone reading your code knows what the methods are for. Doing so tells the reader the criteria for value equality between instances of your class. Someone reading your code that uses equals will immediately know you are checking for value equality.

If you use some other name, it will only confuse readers and cost them extra time reading your JavaDocs to find out what your method is for.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
4

Because equals() is a method of the Object class, which is the superclass of all classes, and due to which it is inherently present in every class you write. Hence every collection class or other standard classes use equals() for object comparsion. If you want your custom class objects to be supported for equality by other classes, you have to override equals() only (since other classes know that for object comparion call equals()). If you are only using your own classes, you might create a new method and make sure everything uses your custom method for comparison.

Mustafa sabir
  • 4,130
  • 1
  • 19
  • 28
2

The equals and hashcode method are special methods, widely used across the java's utility classes specially collection framework, and the wrpper classes e.g. String, Integer have overridden this method, So e.g. if you are placing any Object of your choice which has correct equals and hashcode implementation inside the HashSet, to maintain the property of uniqueness the hashcode will compare with all the existing object in hashset, and if it finds any of the hashcode matching then it looks into the equals method to double check if both are really equal and if that equality check also is pass then incoming object is rejected, but if the hashcode equality check is not passed then hashset will not go for the equals method and straight way place that object into the hashset. So we need to make sure the implementation of equals and hashcode is logically proper.

Vikash Mishra
  • 635
  • 5
  • 7
2

A class like HashMap<T,U> needs to have some means of identifying which item in the collection, if any, should be considered equivalent to a given item. There are two general means via which this can be accomplished:

  1. Requiring that anything to be stored in a collection must include virtual methods to perform such comparison (and preferably provide a quick means (e.g. hashCode()) of assigning partial equivalence classes).

  2. Require that code which creates the collection must supply an object which can accept references to other objects and perform equivalence-related operations upon them.

It would have been possible to omit equals and hashCode() from Object, and have types like HashMap only be usable with key types that implement an equatable interface that includes such members; code which wishes to use collections of references keyed by identity would have to use IdentityHashMap instead. Such a design would not have been unreasonable, but the present design makes it possible for a general-purpose collection-of-collections type which uses HashMap to be usable with things that are compared by value as well as by identity, rather than having to define a separate types for collection-of-HashMap and collection-of-IdentityHashMap.

An alternative design might have been to have a GeneralHashMap type whose constructor requires specifying a comparison function, and have IdentityHashMap and HashMap both derive from that; the latter would constrain its type to equatable and have its identity functions chain to those of the objects contained therein. There would probably have been nothing particularly wrong with that design, but that's not how things were done.

In any case, there needs to be some standard means by which collections can identify items that should be considered equivalent; using virtual equals(Object) and getHashCode() is a way of doing that.

supercat
  • 77,689
  • 9
  • 166
  • 211
1

Question 1

There are Two things. equals() is Located inside Object class Collection framework using equals() and hashcode() methods when comparing objects

Question 2

Yes for comparing two Object. but when You comparing two String Objects using equals() its only checking the value.

Lasitha Benaragama
  • 2,201
  • 2
  • 27
  • 43