Google News
logo
What are some of the best practices while using Java Collections ?


Following are some of the best practices while using Java Collections : 
 
Selecting the appropriate Collection : Before we use a collection, we must choose the most relevant collection for the problem we are seeking to solve. If we pick the wrong one, our program may still run, but it will be inefficient. On the other hand, if we pick the right one, our solution will be a lot simpler and our program will run much faster.
Specifying the initial capacity of the Collection : Almost all collection classes contain an overloaded constructor that determines the collection's initial capacity. That is, if we know exactly how many pieces will be added to the collection, we can define the initial capacity when establishing a new instance.

Using isEmpty() instead of size() : To check if a collection is empty or not we should use the isEmpty() method rather than finding the size of the collection and comparing it with zero. This enhances the readability of the code.

Using Iterators for iterating over the collections : We should use iterators for traversing over the collection elements instead of using a for loop for the same. The reason is that the iterator may throw ConcurrentModificationException if any other thread tries to modify the collection after the iterator has been created. This saves us from bugs.
Using Concurrent Collections over synchronized wrappers : Instead of utilizing the synchronized collections generated by the Collections.synchronizedXXX() methods, we should consider using concurrent collections from the java.util.concurrent package in multi-threaded applications. Because concurrent collections employ various synchronization strategies such as copy-on-write, compare-and-swap, and specific locks, they are designed to give maximum performance in concurrent applications.

Eliminating Unchecked warnings : We should not disregard unchecked warnings from the Java compiler. The ideal practice is to get rid of any warnings that aren't checked.

Favoring Generic types : We should build new methods with generic parameters in mind, and convert existing methods to use type parameters, just as we should with generic types because generic methods are safer and easier.
LATEST ARTICLES