

Public class TreeMap extends AbstractMap implements Required when we need to maintain the insertion order and when we need to implement the LRU cache.Įquals() and hashcode() method need to overwrittenĪlong with equals() and hashcode(), the comparator to implement. Required when we do the sorting and navigable features need as per the use case. Normal processing, faster retrieval ConcurrentHashMap we can use as per the need No, we need to collections utility to make thread safe Sorted order according to the insertion order Sorted order according to the natural ordering Use case: One can use the TreeMap when we need the natural ordering, or we need to sort the record alphabetically or ascending and descending order. TreeMap is an implementation of the map interface, where it follows the Tree data structure which is RedBlack Tree implementation and follows the natural order along with that when we need to handle the caching mechanism. Use Case: LinkedHashMap is useful whenever we need to maintain the ordering of keys to match the ordering of insertion. Linked HashMap is an implementation of the map interface along with the hashing algorithms it also supports the ordering according to the insertion order.Ĭode Snippet: Map map = new LinkedHashMap() Use case: Sometimes when the data is huge and at the same time, we need faster insertion and retrieval because the time complexity is O(1) and regardless considering the order of the data, I would say that in this case, one can use the HashMap.HashMap guaranteed the time complexity of O(1) for insertion and searching.HashMap is an implementation of map interface, where it's utilizing the hashing algorithms to calculate the index position using hashcode() values from the keys.The classes that implement this interface are, TreeSet and ConcurrentSkipListSetĪ staple in Java collections coding interview questions, be prepared to answer this one.For example, NavigableSet interface can navigate the set in reverse order compared to the order defined in SortedSet.It behaves like a SortedSet with the exception that we have navigation methods available in addition to the sorting mechanisms of the SortedSet.

#Tricky java interview questions code#


ArrayList, LinkedList, CopyOnWriteArray are the implementation of List interface.List interface doesn’t provide the thread safety.The list is somewhat like array however length is changing at runtime.One can access any element from its index.The list follows the ordered collection and can contain duplicate elements.Set also adds a stronger contract on the behaviour of the equals and hashCode.HashSet, LinkedHashSet or TreeSet are the implementations of the Set interface.This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards.Set is a collection, which avoids containing duplicate elements.
