Home > database >  Why is the hashCode instance method not named as getHashCode in Java?
Why is the hashCode instance method not named as getHashCode in Java?

Time:12-10

(Please do let me know in the comments if this question no longer fits the guidelines of SO and might require to be closed/deleted)

In order to obtain the hash code of an object in Java, we use the hashCode() method.

To access (private) fields in Java, by standard, we are expected to have separate method with get or set as prefixes based on the kind of operation the method is performing. So why is this different for the hashCode method?

CodePudding user response:

In the end: conflicting paradigms.

Keep in mind that methods such as hashCode() are with java since day 0 more or less. And back then, there wasn't an established standard suggesting: use getters resp. an explicit "methods should be named doWhatever()".

And once released, renaming it to a more appropriate computeHashcode() or something alike would have broken all existing source code.

In other words: there is also a mindset of using very short method names, such as size() in the Collections interface.

CodePudding user response:

The method hashCode() has been introduced with the first Java version, i.e. officially version 1.0.

The getXXX() and setXXX() paradigm was established later as part of the JavaBeans standard. JavaBeans defines a simple yet very useful component model by deriving properties from pairs of getters/setters. JavaBeans was introduced with JDK 1.1.

So hashCode() predates the getter/setter paradigm.

  •  Tags:  
  • java
  • Related