Friday, November 18, 2016

Top 20 Java Collections Interview Questions

Earlier I have shared Java Collection Framework Tutorial, In this article we will learn Collections Framework Interview Questions. Every Java Programmer need to know these Questions and answers to face technical interview. Besides interviews, Java web developer use this collection framework concept to develop web based applications.

1) What are the benefits of  Collections Framework?

Ans:  I have written some of the benefits as fallows:
  1. Collections Framework reduced development effort by using core collection classes rather than implementing our own collection classes.
  2. Reusability and interoperability
  3. Increased code quality with the use of well tested collection framework classes
  4. Reduced effort  for code maintenance by using collection classes shipped with JDK
  5. Increase the performance by providing high-performance implementations of useful data structures and algorithms.

2) Why Collection doesn't extend  Cloneable and Serializable interfaces?

Ans: 

If you Extending Clonable and Serializable interface simply means that you are creating a sub type of the interface and all implementing classes will mandate cloning and serialization making it less flexible and more restrictive. Only specific implementation should make the decision as to whether it can be cloned or serialized and not all.
 Also not everybody will have a reason to have Cloneable collection because if it has very large data,then every unnecessary clone operation will consume a big memory.
 Another reason is that Cloneable and Serializable are very specialized  behavior and so should be implemented only when required.
For example, many concrete classes in collection implement these interfaces. So if you want this feature use these collection classes otherwise use their alternative classes.


3) Why Map  interface doesn't extend Collection interface?

Ans: 

Although Map interface and it's implementations are part of Collections Framework,Map and Collection interfaces are incompatible. If Map extends Collection interface then where are the elements? Map contains Key-Value pairs and it provides methods to retrieve a list of Keys and Values as Collection but it doesn't fit into the group of elements.

4) Difference between iterator and ListIterator?

Ans: 
  • Iterator can traverse in forward direction only whereas  ListIterator can be used to traverse in both directions.
  • ListIterator inherits from iterator interface and comes with extra functions like adding an element,replacing an element,getting index position for previous and next elements
  • We can use iterator to traverse Set and List collections whereas ListIterator can be used with Lists only
 More about :  Java Iterator tutorial
 
5) How to avoid ConcurrentModificationException on while iterating a Collection?

Ans: 

Try to find another alternative iterator which are fail-safe. We can use concurrent colleciton classes from JDK 1.5 or higher to avoid.
ConcurrentModifiactionException on while iterating over a collection,For example CopyOnWriteArrayList instead of ArrayList and ConcurrentHashMap instead of HashMap.

6)   How to reverse a list?

Ans:  You can use reverse() method to reverse a list
Example:  Collections.reverse(list);

7) What are the importance of hashCode() and equals() methods?

Ans:  

HashMap used Key object hashCode() and equals() method to determine the index to put the key-value pair. These methods are also used when we try to get value from HashMap. If these methods are not implemented correctly,two different key's might produce same hashCode() and equals() output and in that case rather than storing it at different location, HashMap will consider them same and overwrite them.
Similarly, all the collection classes that doesn't store duplicate data use hashCode() and equals() to find duplicates,so it is very important to implement them correctly.
The implementation of equals() and hashCode() should fallow these rules:
  • if obj1.equals(obj2) then obj1.hashCode()==obj2.hashCode() should always be true
  • if obj1.hashCode()==obj2.hashCode() is true, it doesn't mean that obj1.equals(obj2) will be true
Recommended To Read Java Collections Framework Tutorial
 
8) Can we use any class as Map Key?

Ans:
We can use any class as Map Key, however following points should be considered before using them.
  • If the class overrides equals() method,it should also override hashCode() method
  • The class should follow the rules associated with equals() and hashCode() for all instances.
  • If a class filed is not used in equals() you should not use in hashCode() method.
  • Best practice for user defined key class is to make it immutable,so that hashCode() value can be cached for fast performance. Also immutable classes make sure that hashCode() and equals() will not change in future that will solve any issue with mutability
 9)Difference between Comparable and Comparator?

Ans: 
  • Comparable provides only one sort of sequence whereas Comparator provides multiple sort of sequences.
  • Comparable provides one method namely compareTo() whereas Comparator provides one method namely compare().
  • Comparable is found in java.lang package whereas Comparator is found in java.util package
  • Comparable will implement Comparable interface,actual class is modified. In Comparator,actual class is not modified.
Recommended to ReadJava Comparator interface tuorial

10) Difference between ConcurrentHashMap and Hashtable?

Ans:
Hashtable and ConcurrentHashMap, both can be used in multi-threading environment but once the size of Hashtable  becomes considerable large performance degrade because for iteration it has to be locked for longer duration.
Since ConcurrentHashMap introduced concept of segmentation,how large it becomes 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.




11) How to make collcetions read only?

Ans:
Use fallowing methods:
Collections.unmodifiableList(list);
Collections.unmodifiableSet(set);
Collections.unmodifiableMap(map);

These methods takes collection parameter and return a new read-only collection with same elements as in original collection

12) How to make collection thread safe?

Ans:

Use below methods to make collection thread safe:
Collections.synchronizedList(list);
Collections.synchronizedSet(set);
Collections.synchronizedMap(map);
Above methods take collection as parameter and return same type of collection which are synchronized and thread safe. 

13) What is UnsupportedOperationException?

Ans:

This exception is thrown on invoked methods which are not supported by actual collection type.

Example: if you make a read-only list using Collection.unmodifiableList(list) and then call add() or remove() method, what should happen. It should clearly throw UnsupportedOperationException.

14)  How can we sort a list of Objects?

Ans:
If we need to sort an array of Objects,we can use Arrays.sort(). If we need to sort a list of objects, we can use Collections.sort(). Both these classes have overloaded sort() methods for natural sorting or sorting based on criteria(using comparator).

Collections internally uses Arrays sorting method, so both of them have same performance except that Collections take sometime to covert list to array.

15) How can we create a synchronized collection from given collection?

Ans:
We can use Collections.synchronizedCollection(Collection c) to get a synchronized(thread-safe) collection backed by the specified collection.

16) What happens On HashMap in java if the size of the HashMap exceeds a given threshold defined by load factor?

Ans:
Similar to other collection classes such as ArrayList, Java HashMap resizes its indexed internal array itself by creating a new bucket array and starts populating the old array values. This process is called rehashing because it also applies hash function to find new bucket location.
 17) What will happen if two different objects have same hash code in HashMap?

Ans:

This is called hash collision. Since hashCode is same,bucket location would be same and collision will occur in HashMap. Since HashMap use LinkedList to store object,this entry  will be stored in LinkedList

18) How will you retrieve value object if two keys will have same hashcode in HashMap?

Ans:

After finding bucket location,we will call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in java HashMap

19) Do you any problem with resizing of HashMap in java during Threshold exceed Scenario?

Ans:

Yes, it might lead to RACE condition

20) What is Difference between Synchronized Collection and Concurrent Collection?

Ans:

one main difference is that Concurrent Collections has better performance than synchronized Collection because they lock only portion of Map to achieve concurrency and Synchronization.


          
     
  
  
  

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...