Original link:
https://dzone.com/articles/top-java-collection-interview-questions-for-2021
hello, everyone!
This post is about "Top Java Collection Interview Questions for 2021", hope it helps you.
Collections in Java
In Java, Collection is a framework that provides an architecture to store and manipulate groups of objects. The “Collection Framework” has been defined in JDK 1.2 and it holds all the collection classes and interfaces in it. The two main interfaces of the Java Collection classes are the Collection interface (java.util.Collection) and the Map interface (java.util.Map). Java Collections can perform all operations on data such as searching, sorting, insertion, manipulation, and so on. Java Collection Framework provides interfaces such as Set, List, Queue, Deque, and classes such as ArrayList, Vector, LinkedList, HashSet, PriorityQueue, TreeSet, and LinkedHashSet.
Need for a Separate Collection Framework
If we don't use the collection framework, the standard methods for grouping Java Objects are Arrays, Vectors, or Hash Tables. All these have no common interface. All of their implementations are defined independently and there is no correlation between them. Thus, it becomes very difficult to remember all the different methods, syntax, and constructors present in different classes.
For example, to add an element in a Vector we use the addElement() function whereas to add an element in a Hashtable we use the put() function.
Advantages of the Collection Framework
Reduces Programming effort: A programmer can focus more on the best use of the collection rather than focusing on the design of the collection. This helps in implementing abstraction.
Improves program speed: Collections provide a high-performance implementation of data structures and this improves performance.
Since Java is such a widely-used programming language, a plethora of big and small organizations base their products using it. So, prepare yourself with basic and advanced level Java questions to ace the interviews.
Here let's take a look at the most asked and a comprehensive set of questions on java.
Some Commonly Asked Interview Questions for Freshers
Question 1: What is Framework in Java?
Answer: A framework is a set of classes and interfaces which provide a ready-made architecture. An optimal object-oriented design always includes a framework with a collection of classes such that all the classes perform the same kind of task.
Question 2: Define Collection Framework in Java.
Answer: The Java Collections Framework is a collection of interfaces and classes which help in storing and processing the data efficiently. Java Collection Framework provides interfaces such as Set, List, Queue, Deque, and classes such as ArrayList, Vector, LinkedList, HashSet, PriorityQueue, TreeSet, and LinkedHashSet.
Question 3: Differentiate between ArrayList and Vector in the Java Collection Framework.
Answer:
ArrayList
It is not synchronized.
It can increase its size by 50% of the size of the array
It is not thread-safe.
It is not a legacy class.
Vector:
It is synchronized.
It can increase its size by doubling its size.
It is thread-safe.
It is a legacy class.
Question 4: Differentiate between Iterator and Enumeration.
Answer:
Iterator
It can traverse both legacy as well as non legacy elements.
It is slower than Enumeration.
It can perform
removeoperations while traversing the collection.It is fail-fast.
Enumeration
It can traverse only legacy elements.
It is faster than an Iterator.
It can perform only
traverseoperations on the collection.It is not a fail-fast.
Question 5: What is the difference between LinkedList and ArrayList?
Answer:
ArrayList
This class implements a list interface.
This class uses a dynamic array for the storage of elements.
Insert and remove operations are O(1) in the best case and O(n) in the worst case. Seek operation(i.e., accessing an element at a specific index) takes O(1) time.
ArrayList works better at storing and accessing data.
LinkedList
This class implements both, list interface and deque interface.
This class uses a doubly-linked list for the storage of elements.
Insert and remove operations give O(1) performance. Seek operation (i.e., accessing an element at a specific index) takes O(n) time.
LinkedList works better at the manipulation of the stored data.
Question 6: Explain the difference between the poll() and remove() method of Queue interface.
Answer: The two methods return and remove the head of the queue. They differ in their behavior only when the queue is empty; remove() throws an exception whereas poll() returns null for an empty queue.
Question 7: Differentiate between Comparable and Comparator.
Answer:
Comparable
It provides
compareTo()method for sorting elements.It is present in the java.lang package.
The logic of sorting must be in the same class whose object we want to sort.
It provides a single sorting sequence.
The actual class is altered.
Comparator
It provides a
compare()method for sorting elements.It is present in the java.util package.
The logic of sorting must be in a different class so as to write different sorting based on different attributes of objects.
It provides multiple sorting sequences.
The actual class is not altered.
Question 8: What is a Stack in terms of computer memory?
Answer: A stack is a special area of a computer's memory that stores temporary variables created by a function. In stack, variables are declared, stored, and initialized during runtime.
Question 9: List collection views of a map interface.
Answer:
The Collection view methods allow a Map to be viewed as a Collection in these three ways:
Key-set view: The Set of keys contained in the Map.
Value-set view: The Collection of values contained in the Map. This Collection is not a Set, because multiple keys can map to the same value.
Entry-set view: The Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry, the type of the elements in this Set.
Question 10: Define EnumSet.
Answer: It is a Set implementation that can be used with enum types. All the elements must come from one enum type specified explicitly or implicitly. It is not synchronized. NULL keys are not allowed.
Question 11: What are the methods to make collection thread-safe?
Answer: The methods are:
Collections.synchronizedList(list);
Collections.synchronizedMap(map);
Collections.synchronizedSet(set);
Question 12: Differentiate between Queue and Deque.
Answer:
Queue
Also known as Single-ended Queue.
Elements in the Queue are added or removed from one end.
Less versatile.
Deque
Also known as Double-ended Queue.
Elements in the Queue are added from either end and can be added and removed from both ends.
More versatile.
Question 13: Differentiate between hashmap and hashtable.
Answer:
Hashmap
Non synchronized, not thread-safe.
Inherits AbstractMap class.
allows one null key and multiple null values.
Traversed by an iterator.
Hashtable
Synchronized, thread-safe.
Inherits Dictionary class.
Doesn't allow any null key or value.
Traversed by an enumerator and iterator.
Question 14: Define Iterator.
Answer: The Iterator() is an interface that provides methods to iterate Collection. It provides a generic way for traversal using elements of the collection and implementing iterator design pattern.
Question 15: What is a navigable map?
Answer: The NavigableMap interface, a member of the Java Collection Framework, belongs to java.util package. It is a subinterface of SortedMap which provides convenient navigation methods like lowerKey, floorKey, ceilingKey, and higherKey. It also helps to create a submap from an existing map.
Question 16: What is peek() of the queue interface?
Answer: Peek() returns the head of the queue. It does not remove any element. It returns null when the queue is empty.
Some Commonly Asked Interview Questions for Experienced Programmers
Question 1: What is a CopyOnWriteArrayList?
Answer: This class is found in java.util.concurrent package and it implements list interface. It makes a cloned copy of the underlying ArrayList to implement all operations and modifications. It is fail-safe and it will never throw ConcurrentModificationException during iteration.
Question 2: When does ConcurrentModificationException occur?
Answer: The java. util. ConcurrentModificationException occurs when a data collection tries to modify while that collection is actively in use, as when something we are iterating on is modified.
Question 3: Why is ConcurrentHashmap better than Hash tables or Synchronized maps?
Answer: ConcurrentHashMap can be safely used in the concurrent multithreaded environment. It performs better than the two mentioned in the question, because only a certain part of the ConcurrentHashMap gets locked, unlike the Hashtable and SynchronizedMap, where the whole of it gets locked.
Question 4: Explain diamond operator.
Answer: Diamond operator helps the compiler to collect the type arguments of a generic class. In Java SE, developers can substitute the parameterized constructor with an empty parameter set (<>) known as the diamond operator.
Question 5: What do you need to do to use a custom object as a key in Collection classes?
Answer: If you use any custom object in Map as a key, you need to override equals() and hashCode() method. On the other hand, if you are storing a custom object in a sorted Collection, you also need to make sure that your equals() method is consistent with compareTo() method.
Question 6: Illustrate iterator vs collection.
Answer: Iterator can only move and access the next elements using next() or remove an element using remove(). Collection, however, can add an element, iterate, remove an element and clear the entire structure using add(), iterator(), remove(), and clear() respectively. There are some boolean methods as well. Iterator is faster than collection since there are fewer operations associated with it.
Question 7: Enlist some features of HashSet.
Answer: HashSet implements Set interface. The underlying data structure is Hashtable. Null elements are allowed, duplicate elements are not allowed. Objects are inserted on the basis of their hashcode.
Question 8: Explain the difference between fail-fast and fail-safe.
Answer:
Fail-fast
Uses the original collection for traversal.
Cannot modify the collection while iterating.
can throw ConcurrentModificationException.
Fail-safe
Uses a copy of the original collection for traversal.
Can modify the collection while iterating.
Does not throw any exception.
Question 9: Differentiate between ArrayBlockingQueue and LinkedBlockingQueue.
Answer:
ArrayBlockingQueue
Bounded blocking queue storing elements in an array.
Higher throughput.
Uses single-lock double condition algorithms.
LinkedBlockingQueue
Optionally bounded blocking queue based on linked nodes.
Lower throughput.
Uses two-lock queue algorithms.
Question 10: How does TreeMap work in Java? Which data structure will you prefer: HashMap or TreeMap?
Answer: TreeMap is a NavigableMap implementation based on Red-Black trees. It uses the Red-Black tree algorithm to sort the TreeMap object keys. We choose according to our requirement. TreeMap is sorted whereas HashMap is faster. Thus, if we want our elements to be ordered, we use a TreeMap, otherwise we use a HashMap.