Tuesday, 2 October 2018

Java Collection Interview Questions



  • How to create Immutable List in java?
    • Once your lis has been initialized, you can do
    • list = Collections.unmodifiableList(list);
  • Why ConcurrentHashMap does not allow null keys and null values ?
    • We all know that ConcurrentHashMap (optimized version of  Hashtable) doesn't allow null key or null values. 
    • The reason behind this implementation is due to ambiguity nature of the ConcurrentMap (ConcurrentHashMap & ConcurrentSkipListMaps) when it comes to multithreading environment. 
    • The main reason is that if map.get(key) returns null, we can't detect whether the key explicitly maps to null vs the key isn't mapped.
    • In ConcurrentHashMap, It might be possible that key 'K' might be deleted in between the get(k) and containsKey(k) calls.
    • if (concurrentHashMap.containsKey(k)) { return concurrentHashMap.get(k); } else { throw new KeyNotPresentException(); }
    • The above example i am  explaining with two thread(1 & 2). In Line 2, after checking thread 1 with the key "K" in concurrentHashMap(Line 1 -contains some value for the key "K"),  it will returns null (if thread 2 removed the key 'K' from concurrentHashMap). Instead of throwing KeyNotPresentException , it actually returns null.
    • As a result, the code will return null as opposed to KeyNotPresentException (Expected Result if key is not present).
  • When to use ConcurrentHashMap in Java?
    • ConcurrentHashMap is best suited when you have multiple readers and few writers
    • If writers greater than readers, or writer is equal to reader, then performance of ConcurrentHashMap effectively reduces to synchronized map or Hashtable.
    •  Performance of CHM drops, because you got to lock all portion of Map, and effectively each reader will wait for another writer, operating on that portion of Map. 
    • ConcurrentHashMap is a good choice for caches, which can be initialized during application start up and later accessed my many request processing threads.
    •  As javadoc states, CHM is also a good replacement of Hashtable and should be used whenever possible, keeping in mind, that CHM provides slightly weeker form of synchronization than Hashtable.
  • How to design a good key for HashMap?
    • If a key()  is overridden  then the corresponding hashcode() must be overridden.
    • Key’s hash code is used primarily in conjunction to its equals() method, for putting a key in map and then searching it back from map. So if hash code of key object changes after we have put a key-value pair in map, then its almost impossible to fetch the value object back from map. It is a case of memory leak. To avoid this, map keys should be immutable. These are few things to create an immutable of class.
    • This is the main reason why immutable classes like String, Integer or other wrapper classes are a good key object candidate.
  • Difference between HashMap and ConcurrentHashMap
    • In concurrentHashMap, the difference lies in internal structure to store these key-value pairs. ConcurrentHashMap has an addition concept of segments. It will be easier to understand it you think of one segment equal to one HashMap [conceptually]. A concurrentHashMap is divided into number of segments [default 16] on initialization. ConcurrentHashMap allows similar number (16) of threads to access these segments concurrently so that each thread work on a specific segment during high concurrency.
    • This way, if when your key-value pair is stored in segment 10; code does not need to block other 15 segments additionally. This structure provides a very high level of concurrency.
  • Difference between HashMap and Collections.synchronizedMap(HashMap)?
    • Sunchronized hash map can be accessed by only one thread at a time.
  • Difference between ConcurrentHashMap and Collections.synchronizedMap( HashMap )?
    • ConcurrentHashMap is consist of internal segments which can be viewed as independent HashMaps, conceptually. All such segments can be locked by separate threads in high concurrent executions. In this way, multiple threads can get/put key-value pairs from ConcurrentHashMap without blocking/waiting for each other.
    • In Collections.synchronizedMap(), we get a synchronized version of HashMap and it is accessed in blocking manner. This means if multiple threads try to access synchronizedMap at same time, they will be allowed to get/put key-value pairs one at a time in synchronized manner.
  • Difference between HashTable and Collections.synchronized(HashMap)?
    • Both are synchronized version of collection. Both have synchronized methods inside class. Both are blocking in nature i.e. multiple threads will need to wait for getting the lock on instance before putting/getting anything out of it.
    • So what is the difference. Well, NO major difference for above said reasons. Performance is also same for both collections.
    • Only thing which separates them is the fact HashTable is legacy class promoted into collection framework. It got its own extra features like enumerators.
  • How to convert an array of String to arraylist?
  • String[] words = {“RAKESH”, “RAVI”,”AZAR”}; List wordList = Arrays.asList(words); //Now you can iterate over the list
  • How to reverse the list?
  • Collections.reverse(list);
  • Can a null element added to a TreeSet or HashSet?
    • Yes
    • A null element can be added only if the Set contains one element,  because when a second element is added then as per set definition a check is made to check duplicate value and comparison with null element will throw NullPointerException.
  • What are IdentityHashMap and WeakHashMap?
    • IdentityHashMap is similar to HashMap except that it uses reference equality when comparing elements. IdentityHashMap class is not a widely used Map implementation. While this class implements the Map interface, it intentionally violates Map’s general contract, which mandates the use of the equals() method when comparing objects. IdentityHashMap is designed for use only in the rare cases wherein reference-equality semantics are required.
    • WeakHashMap is an implementation of the Map interface that stores only weak references to its keys. Storing only weak references allows a key-value pair to be garbage collected when its key is no longer referenced outside of the WeakHashMap. This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated, so it is impossible to do a look-up of that key in a WeakHashMap at some later time and be surprised that its entry has been removed.
  • What are different Collection views provided by Map interface?
    • key set view
    • value set view
    • entry set view
  • How to make a collection read only?
  • Collections.unmodifiableList(list);
  • TreeMap sorted based on the ?
    • Key
  • How to add objects in tree set?
    • While creating the set pass comparator class’s objects as argument.
    • The comparator class’s comparator method should be overridden with needed logic(use properties of the pojo object)
    public static void main(String[] args) { Set set = new TreeSet(new ComparatorSk()); set.add(new Student(2,"sonu")); set.add(new Student(5,"lion")); set.add(new Student(6,"aval")); set.add(new Student(9,"mallan")); set.add(new Student(8,"bilal")); Iterator ir = set.iterator(); while(ir.hasNext()) { Student obj = ir.next(); System.out.println("Id = " +obj.getId()+ " Name = " +obj.getName()); } } public class ComparatorSk implements Comparator { public int compare(Student o1, Student o2) { if(o1.getId() > o2.getId()){ return 1; } else { return -1; } } }
  • Why doesn't Collection extend Cloneable and Serializable?
    • Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but it would be mistake to require it of all Collections. For example, what does it mean to clone a Collection that's backed by a terabyte SQL database? Should the method call cause the company to requisition a new disk farm? Similar arguments hold for serializable
    • If the client doesn't know the actual type of a Collection, it's much more flexible and less error prone to have the client decide what type of Collection is desired, create an empty Collection of this type, and use the addAll method to copy the elements of the original collection into the new one.
  • Why Map interface doesn’t extend Collection interface?
    • Although Map interface and it’s implementations are part of Collections Framework, Map are not collections and collections are not Map. Hence it doesn’t make sense for Map to extend Collection or vice versa.
    • If Map extends Collection interface, then where are the elements? Map contains key-value pairs and it provides methods to retrieve list of Keys or values as Collection but it doesn’t fit into the “group of elements” paradigm
  • What is an Iterator?
    • Iterator interface provides methods to iterate over any Collection. 
    •  We can get iterator instance from a Collection using iterator() method.
    • Iterator  always denies other threads to modify the collection object which is being iterated by it.
    •  Iterators allow the caller to remove elements from the underlying collection during the iteration.
  • What is difference between Enumeration and Iterator interface?
    • Enumeration is twice as fast as Iterator and uses very less memory. 
    • Enumeration is very basic and fits to basic needs. But Iterator is much safer as compared to Enumeration because it always denies other threads to modify the collection object which is being iterated by it.
    • Iterators allow the caller to remove elements from the underlying collection that is not possible with Enumeration. 
  • What is different between Iterator and ListIterator?
    • We can use Iterator to traverse Set and List collections whereas ListIterator can be used with Lists only.
    • Iterator can traverse in forward direction only whereas ListIterator can be used to traverse in both the directions.
    • ListIterator inherits from Iterator interface and comes with extra functionalities like adding an element, replacing an element, getting index position for previous and next elements.
  • What do you understand by iterator fail-fast property?
    • Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element. If there are any modifications found, it throws ConcurrentModificationException
    • All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.
    •  Fail-Fast iterators immediately throw ConcurrentModificationException if there is structural modification of the collection. 
    •  Structural modification means adding, removing or updating any element from collection while a thread is iterating over that collection.
    •  Iterator on ArrayList, HashMap classes are some examples of fail-fast Iterator.
    •  How Fail Fast Iterator works ?
      • To know whether the collection is structurally modified or not, fail-fast iterators use an internal flag called modCount(list.modeCount) which is updated each time a collection is modified.
      • Fail-fast iterators checks the modCount flag whenever it gets the next value (i.e. using next() method), and if it finds that the modCount has been modified after this iterator has been created, it throws ConcurrentModificationException.
  • What is difference between fail-fast and fail-safe?
    • Iterator fail-safe property work with the clone of underlying collection, hence it’s not affected by any modification in the collection.
    • By design, all the collection classes in java.util package are fail-fast whereas collection classes in java.util.concurrent are fail-safe.
    • Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException.
  • How to avoid ConcurrentModificationException while iterating a collection?
    • We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.
  • Why there are no concrete(particular) implementations of Iterator interface?
    • Iterator interface declare methods for iterating a collection but it’s implementation is responsibility of the Collection implementation classes.
    • Every collection class that returns an iterator for traversing has it’s own Iterator implementation nested class.
  • What is UnsupportedOperationException?
    • UnsupportedOperationException is the exception used to indicate that the operation is not supported. It’s used extensively in JDK classes, in collections framework java.util.Collections.
    • UnmodifiableCollection throws this exception for all add and remove operations.
  • What is difference between ArrayList and LinkedList?
    • ArrayList is an index based data structure backed by Array, so it provides random access to it’s elements with performance as O(1) but LinkedList stores data as list of nodes where every node is linked to it’s previous and next node. So even though there is a method to get the element using index, internally it traverse from start to reach at the index node and then return the element, so performance is O(n) that is slower than ArrayList.
    • Insertion, addition or removal of an element is faster in LinkedList compared to ArrayList because there is no concept of resizing array or updating index when element is added in middle.
    • LinkedList consumes more memory than ArrayList because every node in LinkedList stores reference of previous and next elements.
  • Which collection classes provide random access of it’s elements?
    • ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it’s elements. 
  • What is EnumSet?
    • java.util.EnumSet is Set implementation to use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created.
  • Which collection classes are thread-safe?
    • Vector, Hashtable and Stack are synchronized classes, so they are thread-safe and can be used in multi-threaded environment.
    • Java 1.5 Concurrent API included some collection classes that allows modification of collection while iteration because they work on the clone of the collection, so they are safe to use in multi-threaded environment. 
  • What is BlockingQueue?
    • java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.
    • Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.
    • Also BlockingQueue used for producer-consumer problem.
  •  What is Collections Class?
    • ajava.util.Collections is a utility class consists exclusively of static methods that operate on or return collections. 
    • This class contains methods for collection framework algorithms, such as binary search, sorting, shuffling, reverse etc. 
  • What is Comparable and Comparator interface?
    • Comparable interface has compareTo(T obj) method which is used by sorting methods. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as argument.
    • Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one.
    • Comparable helps in preserving default natural sorting, whereas Comparator helps in sorting the elements in some special required sorting pattern.
  • How can we create a synchronized collection from given collection?
  • use Collections.synchronizedCollection(Collection c)
  • What is Big-O notation? Give some examples?
    • The Big-O notation describes the performance of an algorithm in terms of number of elements in a data structure
    • ArrayList get(index i) is a constant-time operation and doesn’t depend on the number of elements in the list. So it’s performance in Big-O notation is O(1).
    • Example 2: A linear search on array or list performance is O(n) because we need to search through entire list of elements to find the element. 
  • Why can’t we write code as List<Number> numbers = new ArrayList<Integer>();?
    • Generics doesn’t support sub-typing because it will cause issues in achieving type safety. That’s why List<T> is not considered as a subtype of List<S> where S is the super-type of T. To understanding why it’s not allowed, let’s see what could have happened if it has been supported.
  • Why can’t we create generic array? or write code as List<Integer>[] array = new ArrayList<Integer>[10];
    • We are not allowed to create generic arrays because array carry type information of it’s elements at runtime. 
    • This information is used at runtime to throw ArrayStoreException if elements type doesn’t match to the defined type. Since generics type information gets erased at runtime by Type Erasure, the array store check would have been passed where it should have failed. Let’s understand this with a simple example code

No comments:

Post a Comment

Search This Blog

Contact us

Name

Email *

Message *