InterviewSolution
| 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:
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
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.
Before using collections, the right collection needs to be chosen according to the problem that needs to be solved.
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.
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.
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.
The initial capacity of a collection is always specified by an overloaded constructor that is contained in almost all concrete collection classes. |
|