Java Interview Notes : Collection Part One
In Java Collections are very important to understand and analysed this will surely help you in completing your development tasks and also get through interviews.
Collection and Map both with their generic versions are the most important interfaces and all other interfaces extend them to get the basic behavior up and running. Set, Queue and List extend Collection and even inherit Iterable interface, all the three can be “foreached”. Map even though a collection does not extend Collection, and is a Key/Value grouping.
Iterator is the interface whose reference is received by Interfaces which extend Collection interface, hence you can call next(), hasNext() and remove() on ArrayList iterators etc.
ConcurrentModificationException is thrown by these iterators whenever they detect that the collection from which they were derived has been structurally changed hence the general-purpose Collections Framework iterators are known as fail-fast.
So to work effectively with collections in Java you need to know at least these fundamental collections,
a) Arrays:
Arrays are found in a majority of languages and are very easy to use. They are directly implemented in the hardware and are very fast for read operations. For adding and removing elements from locations which are arbitrarily located it has to perform a lot of work to shift other elements and hence is slower and is not preferable. If the collection is small its a great option.
b) Hash table:
It a Dictionary implementation, you have a key/value implementation and is useful in a lot of cases. A employee id can be the key and the connected value might be employee name and such other related values.But hash table provides no support for accessing elements by position, but access by content is usually very fast, as are insertion and removal. Hash tables are the backing structure for many Set and Map implementations. HashMap is the most famous implementation used in Java.
c) Linked lists
Arrays have a fixed size but if you need a collection to extend dynamically you need a Linked-list, Linked-list as by the name has cells interconnected and as needed cells are added dynamically. Linked-list are slow to iterate as the chain is needed to be followed to reach an cell of data. but insertion and removal operations can be performed in constant time by rearranging the cell references.They are also used in implementing HashSet, LinkedHashSet, HashMap and other “Linked” data-structures.
d) Tree
This datastructure is modelled around the concept of a tree, it has a root and branches. The tree here has the root on the top and the branches extended below. TreeMap is an implementation which keeps nodes in a sorted order. They are very fast in insertion and retrieval operations. Also removing nodes is fast to achieve. Binary trees, red-black trees are very effective to solve a lot of use cases.
Comments
Post a Comment