1.

Best practices related to Java Collections Framework?

Answer»

Collections in Java is BASICALLY a framework that allows the storage and manipulation of a group of objects by providing an architecture. All the possible operations in Java such as searching, sorting, deletion, insertion etc. can be performed using the Java Collections.

Some of the best practices related to the Collections Framework in Java are given as follows:

  • Using Arrays and Collections utility classes

The Arrays and Collections utility classes provided by the Java Collections Framework should be used as required as they PROVIDE many useful methods to search, sort and MODIFY ELEMENTS in a collection

  • Do not use the classic for loop

Instead of using a classic for loop to iterate a list collection, use an iterator. This is because if the for loop variable is altered inside the loop, it can lead to bugs.

  • Choosing the right collections

Before using collections, the right collection needs to be chosen according to the problem that needs to be solved.

  • Using the Stream API on collections

There is a stream method in every collection in Java 8 that returns a stream of elements. This MEANS that the aggregate functions can be easily performed using the Stream API.

  • Prefer isEmpty() over size()

The isEmpty() method should be preferred over the size() method to check the emptiness of a collection. Even though there is performance difference between these two methods, this is done to enhance the readability of this code.

  • Do not return null in a method that returns a collection

If a method returns a collection, then it should not return null if there is no element in the collection. Instead, it should return an empty collection.

  • Specify initial capacity of a collection if possible

The initial capacity of a collection is always specified by an overloaded constructor that is contained in almost all concrete collection classes.



Discussion

No Comment Found