InterviewSolution
| 1. |
Best Practices while working with Collections in Java |
|
Answer» A group of objects can be stored and manipulated using an architecture that is provided by the Collections API in Java. 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 of while working with Collections in Java are given as follows: 1. CHOOSING the right collections Before using collections, the right collection needs to be chosen according to the problem that needs to be solved. 2. 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 3. 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. 4. 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 a performance difference between these two methods, this is done to enhance the readability of this code. 5. 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. 6. 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. 7. 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. |
|