What is the Java Collection?
A collection (also called as container) is an object that groups multiple elements into a single unit.
What are the basic interfaces of Java Collections Framework?
Collectionis the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn’t provide any direct implementations of this interface. Setis a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards. Listis an ordered collection and can contain duplicate elements. You can access any element from it’s index. List is more like array with dynamic length.
Mapis an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.
Some other interfaces are
Queue, Dequeue, Iterator, SortedSet, SortedMapand ListIterator.
What are differences between Array and ArrayList?
Read our detailed article on Difference between Array and ArrayList
What are differences between ArrayList and Vector?
Read our detailed article on Difference between ArrayList and Vector
Why Map interface does not extend Collection interface?
Map extendsCollection 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 takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements Iterator Design Pattern.
Why there is not method like Iterator.add() to add elements to the collection?
The semantics are unclear, given that the contract for Iterator makes no guarantees about the order of iteration. Note, however, that ListIterator does provide an add operation, as it does guarantee the order of the iteration.
Why Iterator don’t have a method to get next element directly without moving the cursor?
It can be implemented on top of current Iterator interface but since it’s use will be rare, it doesn’t make sense to include it in the interface that everyone has to implement.
What is 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
All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like
What is iterator fail-safe property?
Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure.
Any structural modification done to the iterator affects the copied data structure. Hence original data structure remains structurally unchanged and no
ConcurrentModificationExceptionthrows by the fail safe iterator.
How to avoid ConcurrentModificationException while iterating a collection?
We can use concurrent collection classes to avoid
ConcurrentModificationExceptionwhile iterating over a collection, for example CopyOnWriteArrayListinstead of ArrayList.
How to reverse the List in Collections?
There is a built in reverse method in Collections class . reverse(List list) accepts list as parameter.
What is the difference between poll() and remove() method of Queue interface?
poll()and remove()method from Queue is used to remove the object and returns the head of the queue, there is a subtle difference between them.
If Queue is
empty()then a call to remove()method will throw Exception, while a call to poll()method returns null. By the way, exactly which element is removed from the queue depends upon queue’s ordering policy and varies between different implementation, for example, PriorityQueue keeps the lowest element as per Comparator or Comparable at head position
What is Big-O notation?
The Big-O notation describes the performance of an algorithm in terms of number of elements in a data structure. Since Collection classes are actually data structures, we usually tend to use Big-O notation to chose the collection implementation to use based on time, memory and performance.
Example 1: 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.
What are advantages of iterating a collection using iterator?
For loop does not allow updating the colection(add or remove) whereas Iterator does allow modifying the collection. Also Iterator can be used where there is no clue what type of collections will be used because all collections implement Iterator interface.
What is ConcurrentHashMap?
ConcurrentHashMapis thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtablein terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.
How to create Collections ReadOnly?
We can create collections read only by below methods:Java01234Collections.unmodifiableMap(Map m)Collections.unmodifiableList(List l)Collections.unmodifiableSet(Set s)
What are differences between ArrayList and LinkedList?
Read our detailed article on Difference between ArrayList and LinkedList
Which collection classes are thread-safe?
Vector, Hashtable, Properties 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 Comparable and Comparator interface?
Java provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods.
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. Read more at Comparable in Java with Example
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. Read more at Comparator in Java with Example
What is the difference between Synchronized Collection and Concurrent Collection?
Java 5 has added several new Concurrent Collection classes e.g.
ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueueetc, which has made Interview questions on Java Collection even trickier.
It has synchronized copy of collection e.g. ArrayList, HashMap by using
One Significant difference is that Concurrent Collections has better performance than synchronized Collection because they lock only a portion of Map to achieve concurrency and synchronization.
How HashMap works in Java?
HashMap stores key-value pair in Map.Entry static nested class implementation. HashMap works on hashing algorithm and uses
hashCode()and equals()method in put and get methods.
When we call put method by passing key-value pair, HashMap uses Key
hashCode()with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entry, it uses equals()method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and store this key-value Entry.
When we call get method by passing Key, again it uses the———————————
hashCode()to find the index in the array and then use equals()method to find the correct Entry and return it’s value. Below image will explain these detail clearly.
The other important things to know about HashMap are capacity, load factor, threshold resizing. HashMap initial default capacity is 16 and load factor is 0.75.
Threshold is capacity multiplied by load factor and whenever we try to add an entry, if map size is greater than threshold, HashMap rehashes the contents of map into a new array with a larger capacity.
The capacity is always power of 2, so if you know that you need to store a large number of key-value pairs, for example in caching data from database, it’s good idea to initialize the HashMap with correct capacity and load factor.
What is hash-collision in Hashtable and how it is handled in Java?
Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision.
What is BlockingQueue?
java.util.concurrent.BlockingQueueis 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.
BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem. We don’t need to worry about waiting for the space to be available for producer or object to be available for consumer in BlockingQueue as it’s handled by implementation classes of BlockingQueue.
Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.
What are differences between HashMap and Hashtable?
Read our detailed article on Difference between HashMap and Hashtable
What is Java Priority Queue?
PriorityQueueis an unbounded queue based on a priority heap and the elements are ordered in their natural order or we can provide Comparator for ordering at the time of creation.
PriorityQueue doesn’t allow null values and we can’t add any object that doesn’t provide natural ordering or we don’t have any comparator for them for ordering. Java PriorityQueue is not thread-safe and provided
O(log(n))time for enqueing and dequeing operations.
What is the difference between Iterator and Enumeration?
The main difference between Iterator and Enumeration is that Iterator has
remove()method while Enumeration doesn’t.
Hence, using Iterator we can manipulate objects by adding and removing the objects from the collections. Enumeration behaves like a read only interface as it can only traverse the objects and fetch it .
When to use ArrayList and when to use LinkedList in application?
ArrayList has constant time search operation
O(1). Hence, ArrayList is preferred when there are more get()or search operation .
Insertion , Deletion operations take constant time
O(1)for LinkedList. Hence, LinkedList is preferred when there are more insertions or deletions involved in the application.
What will be the output of below program?Java012345678Map<String, String> testMap = new HashMap<String, String>();System.out.println(testMap.put("key1", "val1"));System.out.println(testMap.put("key1", "val2"));System.out.println(testMap.put("key1", null));
null val1 val2
Note:During a put operation, when we use a key that was already used previously to store a value, it returns the previous value associated with the key.