Introduction to JVM Languages
上QQ阅读APP看书,第一时间看更新

Preparing your classes for the Collections API

As we saw earlier, two important methods of the mother class java.lang.Object are:

  • hashCode()
  • equals(Object other)

These methods are used extensively by all the collections APIs. For performance reasons, and to ensure that the APIs work as expected, it is important that classes that are put inside a Collection object override these methods and provide a good implementation for both. Java programmers who define their own classes must write implementations for both methods themselves; all the other languages covered in this book generally generate implementations for both methods automatically when defining a class.

If you don't like the hashCode() and equals() versions that your JVM language generated for you, then most languages allow you to override the methods manually so that you can still provide your own implementations.

Because Java programmers are the most likely candidates to provide their own implementations, the exact rules that both the methods need to follow are explained in the Java chapter. However, we will still take a quick look at these methods so that we can see how hashing mechanisms are used by many Collection classes.