What are the important methods that are declared in the Collection Interface? How do you iterate around an ArrayList using Iterator? What is the difference between synchronized and concurrent collections in Java?. Also shared the tricky coding interview questions in our previous posts. Today, we will learn about the top 50 java collections interview questions and answers. Looking for Java Collection job? Collection framework provides many interfaces like Set, List, Queue etc and classes like ArrayList, Vector, LinkedList, HashSet etc. Please have a look at our Java Collection job interview questions and answers page to win your job.
|Language:||English, Spanish, French|
|Distribution:||Free* [*Register to download]|
Here I am listing some important java collections interview questions and answers for helping you in .. Download java collections pdf for more information . A set of practical Collections-related Java interview questions. Java Interview Questions iii. 4 Java Collections. 8. What are the basic interfaces of Java Collections Framework? 8. Why.
Most important thing to remember about a List interface - any implementation of the List interface would maintain the insertion order. When an element A is inserted into a List without specifying position and then another element B is inserted, A is stored before B in the List.
When a new element is inserted without specifying a position, it is inserted at the end of the list of elements.
However, We can also use the void add int position, E paramE ; method to insert an element at a specific position. Listed below are some of the important methods in the List interface other than those inherited from Collection interface:.
First and foremost, Map interface does not extend Collection interface. So, it does not inherit any of the methods from the Collection interface. A Map interface supports Collections that use a key value pair. A key-value pair is a set of linked data items: Key-value pairs are used in lookup tables, hash tables and configuration files.
A key value pair in a Map interface is called an Entry. SortedSet Interface extends the Set Interface. Both Set and SortedSet do not allow duplicate elements. Main difference between Set and SortedSet is - an implementation of SortedSet interface maintains its elements in a sorted order.
Set interface does not guarantee any Order.
For example, If elements 4,5,3 are inserted into an implementation of Set interface, it might store the elements in any order. However, if we use SortedSet, the elements are sorted.
The SortedSet implementation would give an output 3,4,5. Important Operations in the SortedSet interface which are not present in the Set Interface are listed below:. SortedMap interface extends the Map interface. In addition, an implementation of SortedMap interface maintains keys in a sorted order. Queue Interface extends Collection interface. Queue Interface is typically used for implementation holding elements in order for some processing.
Queue interface offers methods peek and poll which get the element at head of the queue. The difference is that poll method removes the head from queue also. Iterator interface enables us to iterate loop around a collection.
All collections define a method iterator that gets an iterator of the collection. ArrayList implements the list interface. So, ArrayList stores the elements in insertion order by default. Code like below is permitted because of auto boxing.
Add method by default adds the element at the end of the list. Other option to sort collections is by creating a separate class which implements Comparator interface. There are two ways. First is to use toArray String function. Example below. This creates an array of String's. Vector has the same operations as an ArrayList.
However, all methods in Vector are synchronized. So, we can use Vector if we share a list between two threads and we would want to them synchronized. Linked List extends List and Queue. Other than operations exposed by the Queue interface, LinkedList has the same operations as an ArrayList.
However, the underlying implementation of Linked List is different from that of an ArrayList. ArrayList uses an Array kind of structure to store elements.
So, inserting and deleting from an ArrayList are expensive operations. However, search of an ArrayList is faster than LinkedList. LinkedList uses a linked representation. Each object holds a link to the next element. Hence, insertion and deletion are faster than ArrayList. But searching is slower.
These classes are described in great detail in the video - https: HashSet implements set interface. So, HashSet does not allow duplicates. However, HashSet does not support ordering. The order in which elements are inserted is not maintained. Sachin is Duplicate. So will not be added. LinkedHashSet implements set interface and exposes similar operations to a HashSet.
Difference is that LinkedHashSet maintains insertion order. When we iterate a LinkedHashSet, we would get the elements back in the order in which they were inserted. TreeSet implements this interface. Let's look at an example with TreeSet. Note that elements in TreeSet are sorted. Lower method finds the highest element lower than specified element. Floor method finds the highest element lower than or equal to specified element. Corresponding methods for finding lowest number higher than specified element are higher and ceiling.
HashMap and TreeMap. These classes are explained in detail in this video - https: HashMap implements Map interface — there by supporting key value pairs. TreeMap is similar to HashMap except that it stores keys in sorted order.
We will now insert a Cricketer with key dravid. In sorted order,dravid comes before sachin. So, the value with key dravid is inserted at the start of the Map. We will now insert a Cricketer with key ponting. In sorted order, ponting fits in between dravid and sachin.
Why there is not method like Iterator. 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. What is different between Iterator and ListIterator? 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 are different ways to iterate over a list? We can iterate over a list in two different ways — using iterator and using for-each loop. 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. What is difference between fail-fast and fail-safe? By design, all the collection classes in java.
Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException. How to avoid ConcurrentModificationException while iterating a collection? Check this post for ConcurrentHashMap Example. Why there are no concrete implementations of Iterator interface? This allows collection classes to chose whether iterator is fail-fast or fail-safe. What is UnsupportedOperationException?
UnsupportedOperationException is the exception used to indicate that the operation is not supported. UnmodifiableCollection throws this exception for all add and remove operations.
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.
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. 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.
What is the importance of hashCode and equals methods? HashMap uses 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. The implementation of equals and hashCode should follow these rules. If o1. Can we use any class as Map key? 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. Please refer earlier question for these rules. If a class field is not used in equals , you should not use it 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. What are different Collection views provided by Map interface? The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator. It does not support the add or addAll operations.
The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.
What is difference between HashMap and Hashtable? HashMap and Hashtable both implements Map interface and looks similar, however there are following difference between HashMap and Hashtable. Hashtable is synchronized but HashMap is not synchronized. So HashMap is better for single threaded environment, Hashtable is suitable for multi-threaded environment. LinkedHashMap was introduced in Java 1. Hashtable is considered to be legacy class and if you are looking for modifications of Map while iterating, you should use ConcurrentHashMap.
How to decide between HashMap and TreeMap? For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
What are similarities and difference between ArrayList and Vector? ArrayList and Vector are similar classes in many ways. Both are index based and backed up by an array internally.
Both maintains the order of insertion and we can get the elements in the order of insertion.
The iterator implementations of ArrayList and Vector both are fail-fast by design. ArrayList and Vector both allows null values and random access to element using index number.
These are the differences between ArrayList and Vector. Vector is synchronized whereas ArrayList is not synchronized.