Collection of bad coding practices

Posts Tagged ‘hashcode

‘equals()’ and ‘hashCode()’ are context-sensitive

with 3 comments

equals() and hashCode() implementations should rely only on an internal object state. Making them dependent on other objects, context of use and other external conditions conflicts with the general contracts of consistency:

“For any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false” [*]

“Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer” [*]

Violating those contracts may cause all kinds of weird and unpredictable behavior.

A known example of this antipattern is equals() and hashCode() in implementation where they are depending on information returned by a domain name server, rather than on actual stored URL data.

See also:

Written by Alex

November 24, 2007 at 6:20 am

Posted in Objects

Tagged with , ,

Using URLs in Collections

with one comment objects used as Map keys or Set items can result in a big performance issue. Internal implementation of equals() and hashCode() methods of class performs domain name resolution, so the time of their execution relies on an internet connection speed. If a computer is off-line, the time is nearly equal to a connection timeout (tens of seconds).

The same problem arises every time when URLs equality checking or hash code computation is performed.

Do not use to keep URL values. Use objects or the simple Strings instead.

Read the rest of this entry »

Written by Alex

November 22, 2007 at 12:25 pm

Posted in Collections

Tagged with , , , , , ,

‘equals()’ is overridden while ‘hashCode()’ is not

with 5 comments

If you override equals() in your class, always provide a custom implementation of hashCode() that returns the same hash code value for two or more equal objects:

a.equals(b) → a.hashCode() == b.hashCode()

This is, in fact, a general contract defined by Java API Specification. Violation of this rule (which is likely the case if equals() method is overridden while hashCode() is inherited from Object) may cause numerous bugs and unexpected behaviours.

Note that the reverse rule: two or more unequal objects must have different hash codes, or

!a.equals(b) → a.hashCode() != b.hashCode()

though not required, is also highly recommended to be maintained wherever possible (except for the cases when a number of class instances is known to be greater than Integer.MAX_VALUE). Disregard of this rule (hash collisions) may reduce performance of HashMaps and Hashtables.

Read the rest of this entry »

Written by Alex

November 22, 2007 at 8:37 am

Posted in Objects

Tagged with , ,