Wednesday 1 March 2017

Java Collection Basic Questions Part 2

The Java Collections API's provide Java developers with a set of classes and interfaces that makes it easier to handle collections of... thumbnail 1 summary
The Java Collections API's provide Java developers with a set of classes and interfaces that makes it easier to handle collections of objects.


1) What is difference between an ArrayList and a vector?

a) Synchronization: ArrayList is non-synchronized which means multiple threads can work on ArrayList at the same time. For e.g. if one thread is performing an add operation on ArrayList, there can be an another thread performing remove operation on ArrayList at the same time in a multithreaded environment

while Vector is synchronized. This means if one thread is working on Vector, no other thread can get a hold of it. Unlike ArrayList, only one thread can perform an operation on vector at a time.

b) Resize: A Vector defaults to doubling size of its array . While when you insert an element into the ArrayList ,      it increases
its Array size by 50% .

c) Performance: Vector is slow as it is thread safe . In comparison ArrayList is fast as it is non synchronized . Thus     in ArrayList two or more threads  can access the code at the same time  , while Vector is limited to one thread at a time.

d) fail-fast: First let me explain what is fail-fast: If the collection (ArrayList, vector etc) gets structurally modified by any means, except the add or remove methods of iterator, after creation of iterator then the iterator will throw ConcurrentModificationException. Structural modification refers to the addition or deletion of elements from the collection.

As per the Vector javadoc the Enumeration returned by Vector is not fail-fast. On the other side the iterator and listIterator returned by ArrayList are fail-fast.

e) Who belongs to collection framework really? The vector was not the part of collection framework, it has been included in collections later. It can be considered as Legacy code. There is nothing about Vector which List collection cannot do. Therefore Vector should be avoided. If there is a need of thread-safe operation make ArrayList synchronized as discussed in the next section of this post or use CopyOnWriteArrayList which is a thread-safe variant of ArrayList.

2) What is different between Iterator and ListIterator?

a) Iterator is used for traversing List and Set both.
While ListIterator is used to traverse List only.

b) We can traverse in only forward direction using Iterator.
Using ListIterator, we can traverse a List in both the directions (forward and Backward).

c) We cannot obtain indexes while using Iterator
We can obtain indexes at any point of time while traversing a list using ListIterator using nextIndex() and previousIndex() are used for this purpose.

d) We cannot add element to collection while traversing it using Iterator, it throws ConcurrentModificationException when you try to do it.
We can add element at any point of time while traversing a list using ListIterator.

e) We cannot replace the existing element value when using Iterator.
By using set(E e) method of ListIterator we can replace the last element returned by next() or previous() methods.

f) Methods of Iterator:
  • hasNext()
  • next()
  • remove()

Methods of ListIterator:
  • add(E e)
  • hasNext()
  • hasPrevious()
  • next()
  • nextIndex()
  • previous()
  • previousIndex()
  • remove()
  • set(E e)

3) What is difference between fail-fast and fail-safe?

a)Fail-fast Iterator throws ConcurrentModfiicationException as soon as they detect any structural change in collection during iteration, basically which changes the modCount variable hold by Iterator. While fail-safe iterator doesn't throw CME.

b)Fail-fast iterator traverse over original collection class while fail-safe iterator traverse over a copy or view of original collection. That's why they don't detect any change on original collection classes and this also means that you could operate with stale value.

c)Iterators from Java 1.4 Collection classes e.g. ArrayList, HashSet and Vector are fail-fast while Iterators returned by concurrent collection classes e.g. CopyOnWriteArrayList or CopyOnWriteArraySet are fail-safe.

d)Fail fast iterator works in live data but become invalid when data is modified while fail-safe iterator are weekly consistent.

4) How  Fail  Fast Iterator  come to know that the internal structure is modified ?

The usual way is like this: The collection object keeps a "modCount(version)" variable that is incremented on every modification, and the iterator remembers the last "modification count" that it remembers (either from when the iterator was created, or the last modification that was done through the iterator). Every time the iterator is used, it checks its modification count against the collection's, and if it is different, it knows someone modified the collection without using it, and throws the exception.

Note : The 'remove' method also checks the count but, if successful, resets the count to the new value. It does this so that you can use the 'remove' method to remove an entry WITHOUT getting the exception.

5) What is the difference between ArrayList and LinkedList?

a)Search: ArrayList search operation is pretty fast compared to the LinkedList search operation. get(int index) in ArrayList gives the performance of O(1) while LinkedList performance is O(n).

Reason: ArrayList maintains index based system for its elements as it uses array data structure implicitly which makes it faster for searching an element in the list. On the other side LinkedList implements doubly linked list which requires the traversal through all the elements for searching an element.

b)Deletion: LinkedList remove operation gives O(1) performance while ArrayList gives variable performance: O(n) in worst case (while removing first element) and O(1) in best case (While removing last element).

c)Conclusion: LinkedList element deletion is faster compared to ArrayList.

Reason: LinkedList’s each element maintains two pointers (addresses) which points to the both neighbor elements in the list. Hence removal only requires change in the pointer location in the two neighbor nodes (elements) of the node which is going to be removed. While In ArrayList all the elements need to be shifted to fill out the space created by removed element.

d)Inserts Performance: LinkedList add method gives O(1) performance while ArrayList gives O(n) in worst case. Reason is same as explained for remove.

e)Memory Overhead: ArrayList maintains indexes and element data while LinkedList maintains element data and two pointers for neighbor nodes hence the memory consumption is high in LinkedList comparatively.

6) What is the difference between List and Set?

a)Ordering : List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list.
Set is an unordered collection, it doesn’t maintain any order. There are few implementations of Set which maintains the order such as LinkedHashSet (It maintains the elements in insertion order).

b)DublicateValues : List allows duplicates while Set doesn’t allow duplicate elements. All the elements of a Set should be unique if you try to insert the duplicate element in Set it would replace the existing value.

c)Null Values : List allows any number of null values. Set can have only a single null value at most.

d)Iterator : ListIterator can be used to traverse a List in both the directions(forward and backward) However it can not be used to traverse a Set. We can use Iterator (It works with List too) to traverse a Set.

e)Legacy Class : List interface has one legacy class called Vector whereas Set interface does not have any legacy class.

7) What is the difference between HashSet and TreeSet?

a)Ordering : HashSet stores the object in random order . There is no guarantee that the element will be printed first in the output  which one is inserted first in the HashSet  .
Elements are sorted according to the natural ordering of its elements in TreeSet. If the objects can not be sorted in natural order than use compareTo() method to sort the elements of TreeSet object .

b)Null value : Null value can not be stored in TreeSet while in HashSet it is possible. If one try to store null object in TreeSet object , it will throw Null Pointer Exception.

c)Performance : HashSet take constant time performance for the basic operations like add, remove contains and size.While TreeSet guarantees log(n) time cost for the basic operations (add,remove,contains).

d)Speed : HashSet is much faster than TreeSet,as performance time of HashSet is constant against the log time of TreeSet for most operations (add,remove ,contains and size).

e)Internal implementation : HashSet are internally backed by hashmap. While TreeSet is backed by a TreeMap.

f)Functionality : TreeSet is rich in functionality as compare to HashSet. Functions like pollFirst(),pollLast(),first(),last(),ceiling(),lower() etc. makes TreeSet easier to use than HashSet.

g)Comparision : HashSet uses equals() method for comparison in java while TreeSet uses compareTo() method for maintaining ordering .

8) What is the difference between HashSet and HashMap?

a)Adding or Storing mechanism : HashMap internally uses hashing to add or store objects. HashSet internally uses HashMap object to add or store the objects.

b)Number of objects during add(put) operation :  HashMap requires two objects put(K key , V Value) to add an element to HashMap object.
HashSet requires only one object add(Object o).

c)Performance : HashMap is faster than HashSet because unique key is used to access object .

d)Storage : HashMap Stores data in form of  key-value pair while HashSet Store only objects.

e)Internal implementation : HashSet are internally backed by hashmap. HashMap  is an implementation of Map interface.

f)Duplicates  :  HashSet does not allow duplicate values.If the HashMap previously contain the mapping for the key, the old value is replaced. HashMap  does not allow duplicate keys but allow dublicate values.

9) What is the difference between HashMap and TreeMap?

a)Ordering : HashMap stores the object in random order . There is no guarantee that the element will be printed first in the output  which one is inserted first in the HashMap  .
Elements are sorted according to the natural ordering of its elements in TreeMap. If the objects can not be sorted in natural order than use compareTo() method to sort the elements of TreeMap object .

b)Implementation : Internal HashMap implementation use Hashing. TreeMap internally uses Red-Black tree implementation.

c)Null keys and Null value : TreeMap can not contain null keys but may contain many null values. HashMap can store one null key and many  null values.

d)Performance : HashMap  take constant time performance for the basic operations like get and put i.e O(1). TreeMap provides guaranteed log(n) time cost for the get and put method. Hence HashMap is much faster than TreeMap, as performance time of HashMap is constant against the log time TreeMap for most operations.

e)Interfaces implemented : HashMap implements Map interface while TreeMap implements NavigableMap interface.

10) What is the difference between HashMap and Hashtable?

a)Synchronization or Thread Safe : Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

b)Null keys and null values : Hashtable does not allow null keys or values.  HashMap allows one null key and any number of null values.

c)Iterating the values :  Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.

11) What is the difference between Comparable and Comparator?

a)Sort sequence : Comparable provides single sorting sequence. In other words, we can sort the collection on the basis of single element such as id or name or price etc. Comparator provides multiple sorting sequence. In other words, we can sort the collection on the basis of multiple elements such as id, name and price etc.

b)Methods Used : Comparable provides compareTo() method to sort elements. Comparator provides compare() method to sort elements.

c)Modify Classes : Comparable affects the original class i.e. actual class is modified. Comparator doesn't affect the original class i.e. actual class is not modified.

d)Package : Comparable is found in java.lang package. Comparator is found in java.util package.

e)Objects needed for Comparision : If you see then logical difference between these two is Comparator in Java compare two objects provided to it , while Comparable interface compares "this" reference with the object specified. So only one object is provided which is then compared to "this" reference.

f)Example : We can sort the list elements of Comparable type by Collections.sort(List) method. We can sort the list elements of Comparable type by Collections.sort(List) method.

12) What is difference between Synchronized and Concurrent Collections in Java?

Synchronised collections are the "thread safe" , which addresses synchronization by making all the public methods of the collection "Synchronized". E.G : Collections.synchronizedMap(Map) will be a synchronized map and can be modified by one thread at a time. Synchronized : like a toilet, the object can be used by only one person (thread). However it is sharable even only one person can use it at one time.

Concurrent collections like ConcurrentHashMap are designed for concurrent access from Multiple threads. Instead of synchronizing every method on a common lock, restricting access to a single thread at a time, it uses a finer-grained locking mechanism called lock striping .For example ConcurrentHashMap introduced concept of segmentation, only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete. Concurrent : like pond, where many person (threads) can solve their different needs. Like washerman washes, some take bath and so on.

No comments

Post a Comment