Question:

What are some of the best practices relating to the Java Collection framework ?

Answer:

  • Choosing the right type of the collection to use, based on the application’s needs, is very crucial for its performance. For example if the size of the elements is fixed and know a priori, we shall use an Array, instead of an ArrayList.
  • Some collection classes allow us to specify their initial capacity. Thus, if we have an estimation on the number of elements that will be stored, we can use it to avoid rehashing or resizing.
  • Always use Generics for type-safety, readability, and robustness. Also, by using Generics you avoid the ClassCastException during runtime.
  • Use immutable classes provided by the Java Development Kit (JDK) as a key in a Map, in order to avoid the implementation of the hashCode and equals methods for our custom class.
  • Program in terms of interface not implementation.
  • Return zero-length collections or arrays as opposed to returning a null in case the underlying collection is actually empty.

Keywords:

© 2017 QuizBucket.org