Java is a popular and widely used programming language and platform. It offers a fast, reliable, and secure environment for developing and running applications. If you're getting ready for Java collection interview questions, it's important to focus on coding questions on collections in Java. Understanding these collections coding questions in Java will help you succeed in interviews, as Java collections programming questions are often featured in technical assessments.
Let's discuss the Top Java Collections Interview Questions (2024) together.
What is Collection in Java?
A Collection in Java is a group of objects stored together as a single unit. It provides a way to store, manage, and manipulate a set of items. Java Collections Framework, introduced in JDK 1.2, includes classes and interfaces that make it easier to work with groups of objects. The core interfaces are Collection and Map, which have several implementations like ArrayList, HashSet, and HashMap. Collections support various operations such as searching, sorting, inserting, and deleting, making it a powerful tool for handling data in Java applications.
Java Collections Interview Questions for Freshers
1. What do you mean by Java Collections?
Ans: A collection in Java is a framework that provides an architecture for storing and manipulating a set of objects. JDK 1.2 introduced a new framework called "Collection Framework," which contains all of the collection classes and interfaces.
Collections in Java can perform any data operation, including searching, sorting, inserting, manipulating, and deleting. A collection in Java refers to a single unit of objects. The Collection interface (java.util.Collection) and the Map interface are the two basic "root" interfaces of Java collection classes (java.util.Map). The Java Collection framework provides numerous interfaces (Set, Queue, Deque, List) and classes (Vector, ArrayList, LinkedList, PriorityQueue, TreeSet, HashSet, LinkedHashSet).
2. What is the difference between an Array and a Collection in Java?
Ans: Array and Collection are similar in storing object references and manipulating data, but they differ in several ways. The following are the primary differences between an array and a Collection:
Array in Java
Collection in Java
Arrays have a fixed size; we can't adjust them to match our needs once we've built one. A user cannot change the length of the array at runtime or according to their requirements.
Collections are naturally growable and can be modified to match our specific requirements. We can modify the size dynamically to suit our needs.
Arrays can only store elements of the same data type, i.e., homogeneous.
A collection can hold both homogeneous and heterogeneous components.
Arrays outperform Collections when it comes to performance.
When it comes to performance, Collections aren't as good as Arrays.
Arrays can store both objects and primitives.
A collection can only include object types.
There is no ready-made method support for arrays because they have no underlying data structure.
As every collection class is based on a standard data structure, there are ready-made methods for every performance demand. We are not responsible for the implementation of these methods, which can be used directly.
Arrays are not preferable to Collections when it comes to memory.
When it comes to memory, Collections outnumber Arrays.
3. What is a collection framework in Java?
Ans: The Collection framework in Java provides a framework for storing and managing a collection of objects. It gives developers access to prepackaged data structures as well as data manipulation algorithms. The following is part of the collection framework:
Interfaces
Classes
Algorithms
All of these classes and interfaces support various operations such as searching, sorting, inserting, manipulating, and deleting, making data manipulation extremely simple and quick.
4. What are the advantages of the Collection Framework in Java?
Ans: The following are the various advantages of the Java collection framework:
Advantages
Explanation
Performance
Java's collection framework provides highly effective and efficient data structures, which improves a program's speed and accuracy.
Maintainability
Since the collection framework supports data consistency and interoperability within the implementation, the code developed is simple to maintain.
Extensibility
The Java collection framework allows developers to customize the primitive collection types to meet their specific needs.
Reusability
The classes in the collection framework can easily mix with other kinds, increasing code reusability.
5. What are the different interfaces used in the Collection framework?
Ans: The Java Collection Framework implements several interfaces, the most commonly used of which are the Collection and Map interfaces (java.util.Map).
The following is a list of Collection Framework interfaces: Collection interface: The primary interface is Collection (java.util.Collection), and every collection must implement it. Syntax: public interface Collection<A>extends Iterable Where <A> denotes that this interface is of type Generic.
List interface: The List interface is an ordered collection of items that extends the Collection interface. It has elements that are duplicated. It also enables element access at random. Syntax: public interface List<A> extends Collection<A>
Map interface: A Map (java.util.Map) is a type of element storage that stores key-value pairs. The Collection interface is not implemented by the Map interface. It can only have one unique key, but duplicate elements are allowed. Map interface and Sorted Map are the two interfaces that implement Map in Java.
Set interface: A collection with the Set (java.util.Set) interface cannot include duplicate elements. It can only include inherited Collection interface methods. Syntax: public interface Set<A> extends Collection<A>
Queue interface: The queue data structure is defined by the queue (java.util.Queue) interface, which holds entries in FIFO order (first-in-first-out). Syntax: public interface Queue<A> extends Collection<A>
De-queue interface: It is a two-ended queue. It enables element insertion and removal from both ends. It embeds both stack and queue attributes, allowing it to perform LIFO (last-in-first-out) stack and FIFO (first-in-first-out) queue operations. Syntax: public interface Dequeue<A> extends Queue<A>
6. What is the difference between an ArrayList and a Vector in Java?
Parameters
ArrayList
Vector
Synchronization
The ArrayList cannot be synchronised.
The vector can be synchronised, i.e., which implies that it can only be accessed by one thread at a time.
Data Growth
If the number of elements in an array reaches its maximum, ArrayList increases the array size by 50%.
When an array's size surpasses its maximum, the vector increases by 100%, doubling the current array size.
Performance
Since ArrayList is not synchronised, it is faster than vector operations.
Since vector operations are synchronised, they are slower (thread-safe). When one thread works on a vector, it gains a lock on it, requiring all other threads working on it to wait until the lock is released before continuing.
Traversal
ArrayList can only use Iterator to traverse its elements.
Vector can use both Enumeration and Iterator to traverse its elements.
7. Distinguish between Collection and Collections.
Ans: Collection
Collection in Java(java.util.Collection) is an interface.
It's used to represent a collection of objects as a single entity.
It is the Collection framework's root interface.
It is used to derive the collection framework's data structures.
It's used to depict a group of distinct objects as a single entity.
The collection has been an interface with a static method since Java 8. The Interface also has abstract and default methods.
Collections
Collections in Java(java.util.Collections) is a class.
It's used to define numerous collection object utility methods.
The collections aresynchronizedsynchronizedsynchronizedsynchronized a utility class.
It includes a number of static methods for manipulating data structures.
It defines a variety of helpful collection-related techniques.
It only contains static methods.
8. Explain how Java supports linked lists.
Ans: Java supports two forms of linked lists:
A singly linked list is a form of data structure. Each node in a singly linked list retains the contents of that node as well as a reference/pointer to the next node in the list. There is no reference or pointer to the previous node stored.
TheDoubly Linked Listare a form of a linked list that allows traversal in both directions across the data items. This is made possible by each node having two links, one connecting to the next node and the other connecting to the previous node.
9. What are some recommended practices for working with Java Collections?
Ans: Some best practices for using Java Collections are as follows:
Choosing the Right Collection:Before we utilize a collection, we need to make sure it's the right one for the problem we're trying to address. Our software will still operate if we choose the wrong one, but it will be inefficient. If we choose the appropriate one, though, our solution will be considerably easier, and our program will run much faster.
Specifying the Collection's Initial Capacity: Almost all collection classes have an overloaded constructor for determining the collection's initial capacity. For example, if we know how many items will be added to the collection, we may set the initial capacity of a new instance.
Using isEmpty() instead of size() to check if a collection is empty:Instead of finding the collection's size and comparing it to zero, we should use the isEmpty() method. This improves the code's readability.
Using Iterators to Iterate Over Collections:Instead of using a for loop to iterate over the collection elements, we should use iterators. The reason for this is that if another thread tries to alter the collection after the iterator has been built, the iterator may throw ConcurrentModificationException. This protects us from bugs.
Using concurrent collections instead of synchronized wrappers:In multi-threaded applications, we should consider using concurrent collections from the java.util.concurrent package instead of the synchronized wrappers provided by the Collections.synchronizedXXX() methods. Concurrent collections are designed for providing maximum performance in concurrent applications because they use synchronization mechanisms like copy-on-write, compare-and-swap, and particular locks.
Unchecked warnings must be removed: Warnings from the Java compiler that isn't checked should be taken seriously. Any warnings that haven't been checked should be removed as soon as possible.
Generic types should be preferred:We should design new methods with generic parameters in mind, as well as convert existing methods to use type parameters, just as we should with generic types because generic methods are safer and easier to use than non-generic ones. Generic methods are also useful in the development of APIs that are both general and reusable.
10. What are the differences between an ArrayList and a LinkedList?
Ans: ArrayList
ArrayList makes use of a dynamic array to store elements internally.
ArrayList is inefficient for manipulation because it requires too much.
Element manipulation is slower in ArrayList.
ArrayList is better for storing and retrieving data.
It can only function as a List.
ArrayList allows for random access.
ArrayList uses less memory because it only stores objects.
LinkedList
LinkedList makes use of a doubly linked list to store elements internally.
The manipulation of LinkedList is efficient.
Elements can be manipulated more quickly on LinkedList.
To manipulate data, LinkedList is preferable.
It can function as both a list and a queue.
The LinkedList does not support random access.
LinkedList has a higher memory overhead because it stores both the object and its address.
11. What are the differences between an Iterator and a ListIterator?
Ans: Iterator traverses the elements only forward, whereas ListIterator traverses the elements both forward and backward.
Iterator
ListIterator
The Iterator only moves forward through the elements.
ListIterator traverses the elements both backward and forward.
The Iterator can be applied to List, Set, and Queue objects.
ListIterator can only be used in List.
While traversing the collection, the Iterator can only perform ‘remove’ operations.
While traversing the collection, ListIterator can perform ‘add’, ‘remove’, and ‘set’ operations.
12. What are the differences between a HashSet and a TreeSet?
Ans: Both the HashSet and TreeSet implement the Set interface. The distinctions between the two are listed below.
TreeSet maintains ascending order, whereas HashSet does not.
TreeSet is implemented by a Tree structure, whereas HashSet is supported by a hash table.
TreeSet is outperformed by HashSet. In performance, HashSet is better.
TreeSet is supported by TreeMap, whereas HashSet is supported by HashMap.
13. What are the differences between HashMap and Hashtable?
Hashtable
HashMap
The hashtable is synchronized.
HashMap is not synchronized.
A hashtable cannot have a ‘null’ key or a ‘null’ value.
HashMap can have one or more ‘null’ keys and values.
Hashtable is ‘thread-safe’ and can be shared by multiple threads.
HashMap is not ‘thread-safe’. As a result, it is appropriate for non-threaded applications.
Dictionary Class is inherited by Hashtable.
HashMap derives from AbstractMap.
14. In Java, how are the Collection objects sorted?
Ans: Sorting in Java Collections is accomplished through the use of the Comparable and Comparator interfaces. When the Collections.sort() method is called, the elements are sorted in the natural order specified in the compareTo() method. When the Collections.sort(Comparator) method is used, the objects are sorted based on the Comparator interface's compare() method.
15. What is the distinction between Set and Map?
Ans: The distinctions between the Set and the Map are listed below.
Sets only contain values, whereas Maps contain both keys and values.
Sets have unique values, whereas Maps can have unique Keys but duplicate values.
Set has a single number of null values, whereas Map has a single null key with ‘n’ null values.
16. Explain the Collection framework's hierarchical structure in Java.
Ans: The collection framework hierarchy is comprised of four fundamental interfaces: Collection, List, Set, and Map, as well as two sorting-specific interfaces called SortedSet and SortedMap. The collection framework's interfaces and classes are all contained in java.util package. The Java collection structure is depicted in the diagram below.
Here, ‘e’ stands for extends and ‘i’ stands for implements. Extends: The extends keyword is used to establish inheritance between two classes and two interfaces. Implements: The keyword implements is used to define inheritance between classes and interfaces.
17. What is the distinction between a List and a Set?
Ans: The collection interface is extended by the List and Set. However, there are some distinctions between the two, which are detailed below.
The List can have duplicate elements, whereas the Set has unique items.
The List is an ordered collection that keeps the insertion order, whereas the Set is an unordered collection that gives up the insertion order.
The List interface has a single legacy class, i.e., vector, whereas the Set interface does not have any legacy classes.
The List interface allows 'n' null values, whereas the Set interface only allows one null value.
18. What are the differences between Comparable and Comparator?
Comparable
Comparator
Comparable only provides one type of sequence.
The Comparator provides a variety of sequences.
It has one method called compareTo().
It has one method called compare().
It can be found in the java.lang package.
It is included in the java.util package
When we implement the Comparable interface, the actual class changes.
The actual class remains unchanged.
19. How should one remove duplicates in an ArrayList?
Ans: Duplicates in the ArrayList can be removed in two ways.
Using HashSet: We can remove the duplicate element from the ArrayList using HashSet, but the insertion order will be lost.
Using LinkedHashSet instead of HashSet: We can also keep the insertion order by using LinkedHashSet instead of HashSet.
The LinkedHashSet method is used to remove duplicate elements from an ArrayList. The process of duplicating the elements can be achieved by the following steps:
ArrayList elements are copied to LinkedHashSet.
Then clear the ArrayList using the clear() method, which removes all elements from the list.
Now, copy all of the LinkedHashset elements to ArrayList.
20. What is a priority queue in Java?
Ans: A PriorityQueue is used when the objects are to be processed in order of priority. A Queue is known to use the First-In-First-Out method, but there are times when the queue's components must be handled in order of priority, which is where the PriorityQueue comes in. The PriorityQueue is built on the priority heap. The members of the priority queue are ordered either by natural ordering or by a Comparator provided at the time of queue construction.
Here, ‘e’ stands for extends, and ‘i’ stands for implements. Extends: The extends keyword is used to establish inheritance between two classes and two interfaces. Implements: The keyword implements is used to define inheritance between classes and interfaces.
The PriorityQueue class in Java implements the Serializable, Collection<E>, Iterable<E>, and Queue<E> interfaces.
Java Collection Interview Questions For Experienced
21. Distinguish between fail-fast and fail-safe iterators.
Fail-Fast
Fail-Safe
It is not possible to modify the collection while iterating.
It allows collection changes while iterating.
ConcurrentModificationException may be thrown.
It cannot raise any exceptions.
It traverses the elements using the original collection.
It traverses the elements using an original collection copy.
There is no need for additional memory.
There is a requirement for additional memory.
22. Why doesn't the Map interface extend the Collection Interface or vice versa?
Ans: If Map extends the Collection Interface, "Key-value pairs" may be the only element type for this type of Collection, though this provides a very limited (and ineffective) Map abstraction. You can't ask what value a particular key corresponds to, and you can't delete an entry unless you know what value it corresponds to. Maps' three "Collection view procedures" depict the fact that Maps can be viewed as the Collections (of keys, values, or pairs) (keySet, entrySet, and valueSet). While it is theoretically possible to think of a List as a Map mapping indices to items, doing so has the unintended consequence of changing the Key associated with every element in the List prior to the deleted member. This is also why the Collection cannot be used to extend the Map Interface.
23. Why do we override the equals() method?
Ans: The equals method is used to determine whether two objects are identical. If we want to check the objects based on the property, we must override it.
For example, Employee is a class that has 3 data members: id, name, and salary. However, we want to test the equality of employee objects based on their salaries. The equals() method must then be overridden.
24. List the differences between an Array and an ArrayList in Java.
Ans: The differences between an Array and an ArrayList are:
Arrays are a fundamental feature of Java. ArrayList is a collection system component in Java. As a result, It is used to access array members, whereas ArrayList provides a set of methods for modifying and accessing components.
Although ArrayList is not a fixed-size data structure, Array is. There is no need to specify the size of an ArrayList object when creating it. Even if we set a maximum capacity, we can later add more parts.
Arrays can contain both primitive data types and class objects, depending on how they are defined. In contrast, ArrayList only accepts object entries and not primitive data types. The primitive int data type is converted to an Integer object when we use arraylist.add(1).
Since ArrayList cannot be constructed for primitive data types, its members are always referencing objects at different memory locations. As a result, the actual objects in an ArrayList are never stored in the same location. The references to actual items are kept close together. The type of array determines whether it is a primitive or an object. Actual values for primitive types are continuous regions, while object allocation is equivalent to ArrayList.
Java ArrayList supports a wide range of other operations, including indexOf() and delete(). These functions are not supported by arrays.
25. What do you mean by hash-collision in Hashtable, and how does it work in Java?
Ans: Hash-collision occurs when two keys with the same hash value collide. Two separate entries will be kept in a single hash bucket to avoid collision.
There are two methods for avoiding hash collisions.
Open Addressing
Separate Chaining
26. Can we modify the overridden method's scope in the subclass?
Yes, the scope of the overridden method in the subclass can be changed. However, we must keep in mind that we cannot reduce the method's accessibility. The following consideration must be made while modifying the method's accessibility:
Change the private access specifier to protected, public, or default.
The protected access specifier can be set to public or default.
The default setting can be changed to public.
The public will always remain public.
27. What is method overriding in Java?
Method overriding occurs when a subclass provides a specific implementation of a method that is already offered by its parent class. It is used to implement interface methods and for runtime polymorphism. There are some rules which are necessary for method overriding Java:
The method's name must be the same as in the parent class.
The method's signature must be the same as in the parent class.
An IS-A relationship must exist between two classes.
28. What is composition?
Composition is the holding of a class's reference within another class. When one item includes another, and the contained object cannot exist without the existence of the container object, this is referred to as composition. In other words, composition is a subset of aggregation that represents a stronger relationship between two items. Students, for example, make up a class. A student cannot exist in the absence of a class. There is a composition between the class and the pupils.
29. What are the advantages of Inheritance in Java?
The following are some of the benefits of using inheritance in Java:
Inheritance allows for code reuse. The derived class is not required to redefine the base class's method unless it needs to provide a specific implementation of the method.
Inheritance is required to create runtime polymorphism.
Data hiding is provided by inheritance. By making some data private, the base class can hide it from the descendant class.
Without inheritance, method overriding is impossible. We can provide a specific implementation of a basic method contained by the base class through method overriding.
30. What is the static variable?
The static variable is used to refer to a property that is shared by all objects but is not unique to each one, such as the firm name of employees, the college name of students, and so on. Static variables are allocated memory in the class region just once during class loading. Using a static variable improves the memory efficiency of your program (it saves memory). The static variable belongs to the class, not the object.
31. How does ConcurrentHashMap work in Java?
ConcurrentHashMap is designed for high concurrency by partitioning the map into segments. Each segment is a separate lockable entity, allowing multiple threads to access different segments simultaneously without interference. This design avoids locking the entire map, as seen in Hashtable, thereby improving performance in multithreaded environments. The map uses fine-grained locking, which reduces contention and enhances throughput by allowing concurrent reads and writes.
32. What is the role of NavigableMap in Java Collections?
NavigableMap extends SortedMap and adds methods for efficient navigation within the map. It allows traversal in both ascending and descending order through methods such as lowerKey(), floorKey(), ceilingKey(), and higherKey(). These methods help locate specific entries relative to a given key, facilitating range queries and other operations that require sorted data.
33. How do WeakHashMap and HashMap differ?
WeakHashMap and HashMap differ in how they manage key references, impacting their memory handling and use cases. WeakHashMap uses weak references for its keys, which means that if a key in the map is no longer reachable through strong references, the garbage collector can reclaim the memory associated with that key. This behavior makes WeakHashMap ideal for memory-sensitive caching scenarios where you want unused entries to be automatically removed to free up memory. In contrast, HashMap uses strong references for its keys, meaning that as long as the key is present in the map, it will not be garbage collected, even if no other references to the key exist. This can lead to memory leaks if keys are not explicitly removed from the map. Thus, while WeakHashMap is beneficial for implementing caches where keys should be cleaned up when not in use, HashMap is more suited for scenarios where you need to maintain the keys in memory until you manually manage their removal.
34. What is the purpose of the BlockingQueue interface?
he BlockingQueue interface is used for thread-safe queue operations where threads may need to wait for certain conditions. It provides methods that support waiting for the queue to become non-empty when retrieving an element and for the queue to have available space when adding an element. This is particularly useful in scenarios like the producer-consumer problem, where you need to manage threads that produce and consume items asynchronously.
35. How does TreeMap maintain order?
TreeMap maintains order through the use of a Red-Black tree, which is a self-balancing binary search tree. This tree structure keeps the elements of the TreeMap sorted according to their natural ordering, such as numerical or alphabetical order, or according to a comparator provided when the TreeMap is created. The Red-Black tree ensures that the map remains balanced by performing rotations and color changes during insertions and deletions. This balanced structure allows TreeMap to provide efficient performance for common operations. For example, searching, inserting, and deleting elements all have a time complexity of O(log n), ensuring that the elements are kept in a sorted order while maintaining quick access times. By balancing the tree, TreeMap can offer consistent and predictable performance while managing a sorted collection of key-value pairs.
36. Explain the concept of CopyOnWriteArrayList.
CopyOnWriteArrayList is a thread-safe variant of ArrayList designed for situations where read operations are more frequent than write operations. It works by creating a new copy of the underlying array for every write operation, such as adding or removing elements. This strategy ensures that readers access a stable snapshot of the list while writes are applied to a new copy, thus avoiding synchronization issues and making it suitable for concurrent environments.
37. What is the difference between Synchronized Collection and Concurrent Collection?
Synchronized Collections are thread-safe wrappers around standard collections like ArrayList or HashMap, achieved by synchronizing each method call, which can introduce performance overhead due to the locking mechanism. Concurrent Collections, such as ConcurrentHashMap and CopyOnWriteArrayList, are designed with concurrent access in mind, offering better performance and scalability by using advanced concurrency techniques like fine-grained locking or lock-free algorithms, reducing contention among threads.
38. How does the PriorityBlockingQueue work in Java?
The PriorityBlockingQueue in Java is a thread-safe, unbounded queue that sorts its elements based on their natural ordering or a comparator specified during its creation. It uses a priority heap to manage the order of elements, ensuring that the highest-priority element is always at the front of the queue. Unlike some other queues, PriorityBlockingQueue does not block when adding elements, meaning it can accept new entries without waiting.
However, it does block on retrieval operations if the queue is empty, making it ideal for scenarios where threads need to wait for tasks to become available. This combination of features makes PriorityBlockingQueue suitable for managing tasks in concurrent environments where the priority of tasks needs to be respected while also handling situations where task availability can be intermittent.
39. What are Phantom References in Java, and how do they relate to collections?
Phantom References in Java are a type of reference that allows you to track the lifecycle of objects in memory without preventing their garbage collection. Unlike soft or weak references, phantom references do not give you access to the referenced object. Instead, they are used in conjunction with a ReferenceQueue to receive notifications when an object becomes unreachable. This is particularly useful for implementing memory-sensitive caching mechanisms and performing cleanup operations before an object is actually removed from memory.
40. What is IdentityHashMap in Java?
IdentityHashMap is a unique implementation of the Map interface in Java that uses reference equality (==) instead of the standard object equality (equals) for comparing keys. This means that two keys are considered equal only if they are the exact same object in memory, not if they are equal according to their equals method.
This behavior is particularly useful in situations where you need to ensure that keys are unique based on their memory address, not their content. For example, if you have a situation where the exact identity of objects is important, such as managing a set of unique objects where their identity must be tracked directly, IdentityHashMap is the appropriate choice. It helps when reference equality is crucial, and you want to avoid potential issues that can arise from object equality checks.
Java Collection Programs
1. Write a Java program to remove duplicates from an ArrayList?
This program removes duplicate items from an ArrayList while keeping the original order of elements. It uses a LinkedHashSet to eliminate duplicates and then converts the set back to an ArrayList. The LinkedHashSet preserves the insertion order, ensuring that the final list remains in the same order as the original but without duplicates.
public class RemoveDuplicates { public static void main(String[] args) { ArrayList<String> listWithDuplicates = new ArrayList<>(); listWithDuplicates.add("Apple"); listWithDuplicates.add("Banana"); listWithDuplicates.add("Apple"); listWithDuplicates.add("Orange");
LinkedHashSet<String> set = new LinkedHashSet<>(listWithDuplicates); ArrayList<String> listWithoutDuplicates = new ArrayList<>(set);
System.out.println(listWithoutDuplicates); } }
You can also try this code with Online Java Compiler
In this program, a Map is converted into a List of its entries. The entrySet() method of the Map provides a set view of the key-value pairs. This set is then converted into a list, allowing you to iterate through and process the entries. This approach helps in scenarios where you need to work with map entries as a list.
Java
Java
import java.util.*;
public class MapToList { public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three");
List<Map.Entry<Integer, String>> list = new ArrayList<>(map.entrySet());
3. Write a Java program to sort an ArrayList of Custom Objects by a specific attribute.
This program sorts an ArrayList of custom Student objects based on their age. It uses the Comparator interface to compare the age attribute of Student objects. The sort() method of ArrayList is used to arrange the students in ascending order of their age. This approach is useful when you need to sort objects by a specific property.
public class SortCustomObject { public static void main(String[] args) { ArrayList<Student> students = new ArrayList<>(); students.add(new Student("John", 25)); students.add(new Student("Alice", 20)); students.add(new Student("Bob", 22));
This program reverses the order of elements in a LinkedList. By using the Collections.reverse() method, the program efficiently reverses the list in place. This is helpful for scenarios where you need to process elements in the reverse order they were added.
public class ReverseLinkedList { public static void main(String[] args) { LinkedList<Integer> list = new LinkedList<>(); list.add(1); list.add(2); list.add(3); list.add(4);
5. Write a Java program to find the maximum element in a Collection.
This program finds the maximum value in an ArrayList of integers. It uses the Collections.max() method to get the largest number from the list. This method is useful for quickly determining the highest value in a collection of numbers.
public class MaxElementInCollection { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40);
int maxNumber = Collections.max(numbers);
System.out.println("Maximum number in the collection is: " + maxNumber); } }
You can also try this code with Online Java Compiler
1. Which of the following collections class allows you to access elements based on their position index?
A) Set
B) List
C) Map
D) Queue
Answer: B) List
2. Which class should be used when you need to maintain a collection with natural ordering?
A) HashSet
B) TreeSet
C) ArrayList
D) LinkedList
Answer: B) TreeSet
3. Which method is used to add an element at the beginning of a LinkedList?
A) addFirst()
B) addLast()
C) insertFirst()
D) insertLast()
Answer: A) addFirst()
4. Which of the following is not a part of the Java Collections Framework?
A) ArrayList
B) HashMap
C) Hashtable
D) Dictionary
Answer: D) Dictionary
5. Which collection class is synchronized?
A) ArrayList
B) Vector
C) HashMap
D) HashSet
Answer: B) Vector
Frequently Asked Questions
What questions are asked in collections interview?
Java collections interview questions may cover what is a Java collection, how to implement collections in Java, and what its features are. Apart from that, you must cover the various kinds of collections in Java, as well as working examples.
What are the three types of collections in Java?
The Java Collections Framework defines three basic types of collections: list, set, and map. Depending on the needs of your application, these three types of collections offer distinct ways to store and manage data.
What is the main purpose of Collection in collections?
Aggregate data is stored, retrieved, manipulated, and communicated via collections. They typically represent data objects that are naturally grouped together, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers).
How to practice collections in Java?
Understanding the ideas behind List, Set, and Map is the first step in using collections in Java. Next, create code and run it using different collection implementations. Gain practical experience with collections by using techniques like add, remove, iterate, and sort.
Conclusion
Java is a high-level, object-oriented programming language introduced by Sun Microsystems in 1995. It is versatile, running on various platforms including Windows, macOS, and several UNIX versions. Java is widely used for creating mobile apps, web apps, desktop applications, games, and more.
To excel in programming and perform well in interviews, mastering the fundamentals of the language is essential. This article provides a comprehensive overview of the top Java Collections interview questions for 2023, helping you build a strong foundation in Java Collections.
You can also check out our other interview questions blogs: