37 Java Collections Interview Questions And Answers – Collections in Java Interview Questions For Experienced from Codingcompiler. Test your Java Collections knowledge by answering these tricky interview questions on Java collections. Let’s start learning Java collections interview questions and prepare for Java interviews. All the best for your future and happy learning.
Java Collections Interview Questions
- Define the concept of “collection”.
- What are the benefits of using collections?
- What data can store collections?
- What is the hierarchy of collections?
- What do you know about collections of type List?
- What do you know about collections like Set?
- What do you know about collections like Queue?
- What do you know about collections of type Map, what is their fundamental difference?
- What are the main implementations of List, Set, Map?
- What implementations of SortedSet do you know and what are their features?
- What are the differences / similarities between List and Set?
- What is different / common for the ArrayList and LinkedList classes, when is it better to use ArrayList, and when is LinkedList?
- When is it wise to use an array rather than an ArrayList?
- What is the difference between ArrayList and Vector?
- What do you know about the implementation of the HashSet and TreeSet classes?
- What is the difference between HashMap and TreeMap? How do they work and work? What with access time to objects, what dependences?
- What is a Hashtable, how does it differ from a HashMap? To date, it is deprecated, how to still use the necessary functionality?
- What will happen if we put two values with the same key in Map?
- How is the order of objects in the collection, how to sort the collection?
- Give the definition of “iterator”.
- What is the functionality of the Collections class?
- How to get a non-modifiable collection?
- What collections are synchronized?
- How to get synchronized collection from non-synchronized?
- How to get a collection only for reading?
- Why is the Map not inherited from Collection?
- What is the difference between Iterator and Enumeration?
- How is the foreach loop implemented?
- Why is there no iterator.add () method to add elements to the collection?
- Why is there no method in the iterator class to get the next item without moving the cursor?
- What is the difference between Iterator and ListIterator?
- What are the ways to iterate through all the elements of the List?
- What is the difference between fail-safe and fail-fast properties?
- What should I do to prevent a ConcurrentModificationException?
- What is the stack and the queue, what are the differences between them?
- What is the difference between Comparable and Comparator interfaces?
- Why collections do not inherit the Cloneable and Serializable interfaces?
Related Java Interview Questions
- Java Exceptions Interview Questions
- Java OOPS Interview Questions
- Core Java Interview Questions
- JSF Interview Questions
- JSP Interview Questions
- JPA Interview Questions
- Spring Framework Interview Questions
- Spring Boot Interview Questions
- Core Java Multiple Choice Questions
- 60 Java MCQ Questions And Answers
- Aricent Java Interview Questions
- Accenture Java Interview Questions
- Advanced Java Interview Questions For 5 8 10 Years Experienced
- Core Java Interview Questions For Experienced
Java Collections Interview Questions & Answers
The theme of the Java collections is incredibly extensive, and in order to answer each question a separate article is deeply needed for almost every question. I recommend reading the additional material indicated in the responses.
1. Define the concept of “collection”.
Collections / containers in Java are called classes whose main purpose is to store a set of other elements.
2. What are the benefits of using collections?
Arrays have significant drawbacks. One of them is the final size of the array, as a result, the need to monitor the size of the array. Another is indexing, which is not always convenient, since limits the ability to add and delete objects.
To get rid of these shortcomings for several decades, programmers have been using recursive data types , such as lists and trees . The standard set of Java collections serves to relieve the programmer from the need to independently implement these types of data and provides it with additional features.
3. What data can store collections?
Collections can store any reference data types.
4. What is the hierarchy of collections?
It should be noted here that interface Map is not part of the interface Collection hierarchy.
With Java 1.6, the TreeSet and TreeMap classes implement the NavigableSet and NavigableMap interfaces, which extend the SortedSet and SortedMap interfaces, respectively (SortedSet and SortedMap extend Set and Map).
5. What do you know about collections of type List?
List is an ordered list. Objects are stored in the order they are added to the list. Access to the elements of the list by index.
6. What do you know about collections like Set?
Set – a set of non-repeating objects. In the collection of this type only one reference of the type null is allowed .
7. What do you know about collections like Queue?
Queue is a collection designed to store items in the order they need to be processed. In addition to the basic operations of the Collection interface, the queue provides additional insertion, retrieval, and control operations.
Queues are usually, but not necessarily, ordered elements in a FIFO (first-in-first-out, “first in, first out”) order.
The offer () method inserts an item into the queue; if that fails, it returns false . This method differs from the Add ()method of the Collection interface in that the add () method can unsuccessfully add an element only using unchecked exceptions.
The remove () and poll () methods remove the top of the queue and return it. Which item will be deleted (first or last) depends on the queue implementation. The remove () and poll () methods differ only in the behavior when the queue is empty: the remove () method throws an exception, and the poll () method returns null .
The element () and peek () methods return (but do not remove) the top of the queue.
java.util.Queue <E> implements a FIFO buffer. Allows you to add and retrieve objects. In this case, objects can be obtained in the order in which they were added.
Implementations : java.util.ArrayDeque <E> , java.util.LinkedList <E> .
java.util.Deque <E> inherits java.util.Queue <E> . Bidirectional turn. Allows you to add and remove objects from two ends. It can also be used as a stack.
Implementations : java.util.ArrayDeque <E> , java.util.LinkedList <E> .
Related Java Tutorials For Beginners
Introduction to Java Programming
Java Keywords Tutorial For Beginners
Java Data Types Tutorial For Beginners
Java Operators Tutorial For Beginners
Java Control Flow Statements Tutorial
Java Class Tutorial For Beginners
Java Exceptions Tutorial For Beginners
Java Annotations Tutorial For Beginners
Java Generics Tutorial For Beginners
Java Enumeration Tutorial For Beginners
Java Class Instance Tutorial For Beginners
8. What do you know about collections of type Map, what is their fundamental difference?
The java.util.Map <K, V> interface is used to map each element from one set of objects (keys) to another (values). Moreover, each element of the set of keys is mapped to exactly 1 element of the set of values. At the same time, one element from the set of values may correspond to 1, 2 or more elements from the set of keys. The java.util.Map <K, V>interface describes the functionality of associative arrays.
Implements : java.util.HashMap <K, V> , java.util.LinkedHashMap <K, V> , java.util.TreeMap <K, V> , java.util.WeakHashMap <K, V> .
java.util.SortedMap <K, V> inherits java.util.Map <K, V> . Implementations of this interface provide storage of key set elements in ascending order (see java.util.SortedSet). Implementations : java.util.TreeMap <K, V> .
9. What are the main implementations of List, Set, Map?
Interface | Class / Implementation | Description |
List | ArrayList | List |
Linkedlist | List | |
Vector | Vector | |
Stack | Stack | |
Set | Hashset | Lots of |
Treeset | Lots of | |
SortedSet | Sorted set | |
Map | Hashmap | Map / Dictionary |
Treemap | Map / Dictionary | |
SortedMap | Sorted dictionary | |
Hashtable | Hash table |
Top Java Collections Interview Questions And Answers
10. What implementations of SortedSet do you know and what are their features?
java.util.SortedSet <E> inherits java.util.Set <E> . Implementations of this interface, in addition to monitoring the uniqueness of stored objects, support them in ascending order. The order relationship between objects can be defined using either the java.lang.Comparable <T> interface’s compareTo method , or a special comparator class that inherits the java.util.Comparator <T> interface .
Implementations: java.util.TreeSet <E> is a collection that stores its elements as ordered by the values of the tree. TreeSet encapsulates a TreeMap, which in turn uses a balanced binary red-black tree to store items. TreeSet is good because the operations add, remove, and contains take guaranteed log (n) time.
11. What are the differences / similarities between List and Set?
Both are inherited from Collection , which means they have the same set of method signatures. List stores objects in the order of insertion, the item can be obtained by index. Set cannot store the same elements.
12. What is different / common for ArrayList and LinkedList when it is better to use ArrayList, and when is LinkedList?
ArrayList is implemented internally as a regular array . Therefore, when inserting an element into the middle, you must first move all elements one after it, and only then insert a new element into the vacant space. But it quickly implements taking and changing an element — get, set operations — because in them we simply refer to the corresponding element of the array.
LinkedList is implemented internally in a different way. It is implemented as a linked list : a set of separate elements, each of which stores a link to the next and previous elements.
To insert an element in the middle of such a list, it is enough to change the links of its future neighbors. But to get the item with the number 130, you need to walk consistently on all objects from 0 to 130. In other words, the operation set and get immediately implemented very slowly . Look at the table:
Description | Operation | ArrayList | Linkedlist |
Taking item | get | Quickly | Slow |
Item assignment | set | Quickly | Slow |
Add item | add | Quickly | Quickly |
Insert item | add (i, value) | Slow | Quickly |
Delete item | remove | Slow | Quickly |
If you need to insert (or delete) in the middle of the collection a lot of elements, it is better to use LinkedList. In all other cases – ArrayList.
LinkedList requires more memory to store the same number of elements, because besides the element itself, there are also pointers to the next and previous elements of the list, whereas in ArrayList the elements just go in order.
13. When is it wise to use an array rather than an ArrayList?
In short, Oracle writes – use ArrayList instead of arrays. If you need to answer this question differently, you can say the following: arrays can be faster and eat less memory.
Lists lose performance due to the ability to automatically increase in size and related checks. Plus, the list size does not increase by 1, but by a larger number of elements (+15) *. Also, access to [10] in an array can be faster than calling get (10) on a list.
* The reader has sent a comment. “ArrayList has a 1.5-fold increase. int newCapacity = oldCapacity + (oldCapacity >> 1); “.
14. What is the difference between ArrayList and Vector?
Vector deprecated. At Vector, some methods are synchronized and therefore they are slow. In any case, Vector is not recommended at all.
Advanced Java Collections Interview Questions And Answers
15. What do you know about the implementation of the HashSet and TreeSet classes?
The name Hash … comes from the concept of a hash function. A hash function is a function that narrows down the set of values of an object to a subset of integers. The Object class has a hashCode () method , which is used by the HashSet class to efficiently allocate objects to the collection. In classes of objects stored in a HashSet , this method must be overridden.
HashSet is based on a hash table, and TreeSet is based on a binary tree.
HashSet is much faster than TreeSet (constant time versus logarithmic for most operations like add , remove , contains), but TreeSet guarantees the ordering of objects. Both are not synchronized.
Hashset
-
- provides constant time for add () , remove () , contains () and size ()
-
- the order of the elements in the container may change
- container iteration performance depends on capacity and “load factor” (it is recommended to leave the load factor as the default value of 0.75, which is a good compromise between the access time and the amount of stored data)
Treeset
-
- time for basic operations add () , remove () , contains () – log (n)
-
- guarantees the order of the elements
-
- does not provide any parameters for performance tuning
- provides additional methods for an ordered list: first () , last () , headSet () , tailSet () , etc.
Valid response to StackOverflow https://stackoverflow.com/questions/1463284/hashset-vs-treeset
16. What is the difference between HashMap and TreeMap? How do they work and work? What with the time of access to objects, which dependencies?
In general, the answer about HashSet and TreeSet fits this question.
HashMap runs strictly faster than TreeMap .
TreeMap is implemented on a red-black tree, the time to add / search / delete an element is O (log N), where N is the number of elements in the TreeMap at the moment.
With HashMap , the access time to an individual element is O (1), provided that the hash function ( Object.hashCode ()) is normally defined (which is true in the Integer case ).
A general recommendation is to use HashMap if orderliness is not needed . The exception is the situation with real numbers, which are almost always very bad as keys.
For them, you need to use a TreeMap , having first set a comparator for it, which compares real numbers as it is necessary in this task. For example, for ordinary geometric problems, two real numbers can be considered equal if they differ by no more than 1e-9.
17. What is a Hashtable, how does it differ from a HashMap? To date, it is deprecated, how to still use the necessary functionality?
Some HashTable methods are synchronized, so it is slower than a HashMap .
-
- HashTable is synchronized, but HashMap is not.
-
- HashTable does not allow null keys or values. HashMap allows you to have one null key and as many null values as you like.
- In HashMap is a subclass of LinkedHashMap , which adds the ability to iterate. If you need this functionality, you can easily switch between classes.
General note – it is not recommended to use HashTable even in multi-threaded applications. For this there is a ConcurrentHashMap .
https://stackoverflow.com/questions/40471/differences-between-hashmap-and-hashtable
18. What will happen if we put two values with the same key in Map?
The last value overwrites the previous one.
19. How is the order of objects in the collection, how to sort the collection?
The TgeeMar class fully implements the SortedMap interface . It is implemented as a binary search tree, so its elements are stored in an ordered manner. This greatly speeds up the search for the desired item. The order is set either by the natural following of elements, or by an object that implements the Comparator comparison interface .
There are four constructors in this class:
TgeeMar () – creates an empty object with a natural order of elements;
TreeMar (Comparator с) – creates an empty object, in which the order is given by the object of comparison with;
ТеееМар (Map f) – creates an object containing all elements of the map f, with the natural order of its elements;
TeeMar (SortedMap sf) – creates an object containing all the sf display elements in the same order.
The Comparator interface describes two comparison methods:
int compare (Object obj1, object obj2) – returns a negative number if obj1 is in some sense less than obj2 ; zero if they are considered equal; positive number if obj1 is greater than obj2 . For readers familiar with set theory, let’s say that this comparison method has the properties of identity, antisymmetry and transitivity;
boolean equals (Object obj) – compares this object with the object obj , returning true if the objects match in any sense specified by this method.
For each collection, you can implement these two methods by specifying a specific way of comparing elements, and define an object of the SortedMap class by the second constructor. Elements of the collection will be automatically sorted in the specified order.
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public static void main(String[] args) {
Comparator comparator = new Comparator<String>() { @Override public int compare(String obj1, String obj2) { if (obj1 == null) { return -1; } if (obj2 == null) { return 1; } if (obj1.equals(obj2)) { return 0; } return obj1.compareTo(obj2); } }; TreeMap<String, String> treeMap1 = new TreeMap<>(comparator); //or TreeMap<Integer, String> treeMap = new TreeMap<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(o1,o2); } }); } |
Java Collections Interview Questions And Answers For Experienced
20. Give the definition of “iterator”.
Iterator – an object that allows you to iterate over the elements of the collection. For example, foreach is implemented using an iterator. One of the key methods of the Collection interface is the Iterator <E> iterator () method . It returns an iterator — that is, an object that implements the Iterator interface .
The Iterator interface has the following definition:
1
2 3 4 5 |
public interface Iterator <E>{
E next(); boolean hasNext(); void remove(); } |
21. What functionality does the Collections class represent?
Some of the methods
Method signature | Description |
Collections.sort (List myList) | Sorts the list in natural order. |
Collections.sort (List, Comparator c) | Sort using a comparator. |
Collections.shuffle (List myList) | Shuffles the collection in random order. |
Collections.reverse (List myList) | Flips the collection in reverse order. |
Collections.binarySearch (List mlist, T key) | search in a collection by key using binary search. |
Collections.copy (List dest, List src) | Copies the src source collection to dest. |
Collections.frequency (Collection c, Object o) | Returns the number of instances of the object in the collection. |
Collections.synchronizedCollection (Collection c) | Returns a synchronized (thread safe) collection. |
22. How to get a non-modifiable collection?
A read-only collection can be obtained using the methods:
1
2 3 4 5 6 7 8 9 10 |
public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
return new UnmodifiableSortedSet<>(s); } public static <T> List<T> unmodifiableList(List<? extends T> list) { return (list instanceof RandomAccess ? new UnmodifiableRandomAccessList<>(list) : new UnmodifiableList<>(list)); } for each type (Map, SortedMap etc.) |
23. What collections are synchronized?
To do this, use the package Concurrent . And so @Deprecated HashTable , Vector .
24. How to get synchronized collection from non-synchronized?
Use the following methods:
-
- Collections.synchronizedList (list) ;
-
- Collections.synchronizedSet (set) ;
- Collections.synchronizedMap (map) ;
They all take a collection as a parameter, and return a thread-safe collection with the same elements inside.
1
2 3 4 5 |
public static <T> Set<T> synchronizedSet(Set<T> s) {
return new SynchronizedSet<>(s); } for each type of collection etc. |
Java Collection Interview Questions And Answers For 3 Years Experience
25. How to get a collection only for reading?
Use the following methods:
-
- Collections.unmodifiableList (list) ;
-
- Collections.unmodifiableSet (set) ;
- Collections.unmodifiableMap (map) ;
They all take the collection as a parameter, and return the collection as read-only with the same elements inside.
26. Why is the Map not inherited from Collection?
They are not compatible, because created for various data structures. Map uses a key-value pair.
27. What is the difference between Iterator and Enumeration?
Enumeration is twice as fast as Iterator and uses less memory. Iterator is thread-safe because does not allow other threads to modify the collection when iterating. Enumeration can only be used for read-only collections. It also has no remove () method ;
Enumeration: hasMoreElement () , nextElement ()
Iterator: hasNext () , next () , remove ()
28. How is the foreach loop implemented?
Implemented based on Iterator .
1 | for (type iter_per: collection) block_operators |
29. Why is there no iterator.add () method to add elements to the collection?
The iterator’s only task is to iterate over the collection. Each collection has an add () method that you can use. It makes no sense to add this method to the iterator, because the collections can be ordered and unordered, and the add ()method should be organized differently.
Java Collection Interview Questions And Answers For 5 year Experience
30. Why is there no method in the iterator class to get the next item without moving the cursor?
An iterator is similar to a pointer with its main operations: it points to a separate item in the collection of objects (provides access to the item ) and contains functions for moving to another item in the list (the next or previous one).
A container that implements support for iterators should provide the first element of the list, as well as the ability to check whether all elements of the container have been enumerated (whether the iterator is finite). Thus, without a cursor, it is simply impossible to realize an error-free movement around the collection.
31. What is the difference between Iterator and ListIterator?
There are three differences:
-
- Iterator can be used to iterate over the elements Set , List and Map . In contrast, the ListIterator can only be used to iterate through the elements of the List collection.
-
- Iterator allows you to iterate over elements in one direction only, using the next () method . While the ListIterator allows you to iterate through the list in both directions, using the methods next () and previous ()
- With the ListIterator, you can modify the list by adding / removing elements using the add () and remove ()methods . Iterator does not support this functionality.
32. What are the ways to iterate through all the elements of the List?
There are 4 ways:
-
- Loop with iterator
-
- For loop
-
- Extended for loop
- While loop
33. What is the difference between fail-safe and fail-fast properties?
In contrast to fail-fast, the fail-safe iterators do not raise any exceptions when the structure is changed, because they work with a collection clone instead of the original.
The CopyOnWriteArrayList collection iterator and the keySet iterator of the ConcurrentHashMap collection are examples of fail-safe iterators.
34. What should I do to prevent a ConcurrentModificationException?
First of all, you can choose another iterator that works on the principle of fail-safe. For example, if you use List , you can take ListIterator . If you need an outdated collection, then use enumerators.
In the event that the above does not suit you, you have three options:
When using JDK 1.5 or higher, the classes ConcurrentHashMap and CopyOnWriteArrayList are suitable for you . This is the best option.
You can convert a list into an array and
iterate through an array. You can block list changes for the duration of the search using a synchronized block.
Note that the last two options will negatively affect performance.
35. What is the stack and the queue, what are the differences between them?
Collections created to store items for further processing. In addition to the basic operations of the Collection interface , queues support additional operations of adding, deleting, and checking the state of an item.
Usually, but not necessarily, the queues work according to the FIFO principle – the first to come, the first to leave.
The stack is almost like a queue, but it works on the principle of LIFO – the last to come, the first to leave.
Regardless of the order of addition / removal, the head of the queue is an element that will be removed when calling the methods remove () or poll () . Also note that Stack and Vector are both thread safe.
Usage: use the queue if you want to process the stream of elements in the same order in which they arrive. Good for job list and request processing.
Use a stack if you want to put and delete items only from the top of the stack, which is useful in recursive algorithms.
36. What is the difference between Comparable and Comparator interfaces?
In Java, all collections that support automatic sorting use comparison methods to properly sort items. As an example of such classes, we can specify a TreeSet , TreeMap , etc.
In order to sort the elements, the class must implement the Comparator or Comparable interfaces. That is why wrapper classes like Integer , Double, and String implement the Comparable interface .
The Comparable interface helps preserve natural sorting, whereas the Comparator allows you to sort items by different special patterns. A comparator instance is usually passed to the collection designer, if the collection supports it.
It should be noted that the Comparable interface can be implemented by the elements of the collection or the Map keys, and the Comparator is implemented by a separate object (this is convenient since you can prepare several implementations for different sorting rules without changing the code of the Map collection / key elements).
37. Why the collections do not inherit the Cloneable and Serializable interfaces?
Well, the simplest answer is “because it is not necessary.” The functionality provided by Cloneable and Serializable interfaces is simply not needed for collections. (It’s worth making an exception for ArrayList and LinkedList, which implement them).
Another reason is that the Cloneable subclass is not always needed because each cloning operation consumes a lot of memory, and inexperienced programmers can spend it without understanding the consequences.
And the last reason – cloning and serialization are very narrowly specific operations, and they need to be implemented only when necessary. Many collection classes implement these interfaces, but there is absolutely no need to lay them out for all collections in general. If you need cloning and serialization – just use the classes where it is, if not, the other classes.
Must Read Java Interview Questions Books
RELATED INTERVIEW QUESTIONS
- Java Exceptions Interview Questions
- Java OOPS Interview Questions
- Core Java Interview Questions
- JSF Interview Questions
- JSP Interview Questions
- JPA Interview Questions
- Spring Framework Interview Questions
- Spring Boot Interview Questions
- Core Java Multiple Choice Questions
- 60 Java MCQ Questions And Answers
- Aricent Java Interview Questions
- Accenture Java Interview Questions
- Advanced Java Interview Questions For 5 8 10 Years Experienced
- Core Java Interview Questions For Experienced
- GIT Interview Questions And Answers
- Network Security Interview Questions
- CheckPoint Interview Questions
- Page Object Model Interview Questions
- Apache Pig Interview Questions
- Python Interview Questions And Answers
- Peoplesoft Integration Broker Interview Questions
- PeopleSoft Application Engine Interview Questions
- RSA enVision Interview Questions
- RSA SecurID Interview Questions
- Archer GRC Interview Questions
- RSA Archer Interview Questions
- Blockchain Interview Questions
- Commvault Interview Questions
- Peoplesoft Admin Interview Questions
- ZooKeeper Interview Questions