Java Collections Interview Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Java Collections Interview Questions

In Java, collection interview questions are most asked by the interviewers. Here is the
list of the most asked collections interview questions with answers.

1) What is the Collection framework in Java?


Collection Framework is a combination of classes and interface, which is used to
store and manipulate the data in the form of objects. It provides various classes such
as ArrayList, Vector, Stack, and HashSet, etc. and interfaces such as List, Queue, Set,
etc. for this purpose.

2) What are the main differences between array and collection?


Array and Collection are somewhat similar regarding storing the references of
objects and manipulating the data, but they differ in many ways. The main
differences between the array and Collection are defined below:

o Arrays are always of fixed size, i.e., a user can not increase or decrease the
length of the array according to their requirement or at runtime, but In
Collection, size can be changed dynamically as per need.
o Arrays can only store homogeneous or similar type objects, but in Collection,
heterogeneous objects can be stored.
o Arrays cannot provide the ?ready-made? methods for user requirements as
sorting, searching, etc. but Collection includes readymade methods to use.

3) Explain various interfaces used in Collection framework?


Collection framework implements various interfaces, Collection interface and Map
interface (java.util.Map) are the mainly used interfaces of Java Collection Framework.
List of interfaces of Collection Framework is given below:
1. Collection interface: Collection (java.util.Collection) is the primary interface, and
every collection must implement this interface.
Syntax:
public interface Collection<E>extends Iterable
Where <E> represents that this interface is of Generic type
2. List interface: List interface extends the Collection interface, and it is an ordered
collection of objects. It contains duplicate elements. It also allows random access of
elements.
Syntax:
public interface List<E> extends Collection<E>
3. Set interface: Set (java.util.Set) interface is a collection which cannot contain
duplicate elements. It can only include inherited methods of Collection interface
Syntax:
public interface Set<E> extends Collection<E>

1|Page
Queue interface: Queue (java.util.Queue) interface defines queue data structure,
which stores the elements in the form FIFO (first in first out).
Syntax:
public interface Queue<E> extends Collection<E>
4. Dequeue interface: it is a double-ended-queue. It allows the insertion and
removal of elements from both ends. It implants the properties of both Stack and
queue so it can perform LIFO (Last in first out) stack and FIFO (first in first out) queue,
operations.
Syntax:
public interface Dequeue<E> extends Queue<E>
5. Map interface: A Map (java.util.Map) represents a key, value pair storage of
elements. Map interface does not implement the Collection interface. It can only
contain a unique key but can have duplicate elements. There are two interfaces which
implement Map in java that are Map interface and Sorted Map.

4) What is the difference between ArrayList and Vector?


No. ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayList is not a legacy class. Vector is a legacy class.
ArrayList increases its size by 50% of Vector increases its size by doubling the
3)
the array size. array size.
ArrayList is not ?thread-safe? as it is Vector list is ?thread-safe? as it?s every
4)
not synchronized. method is synchronized.

5) What is the difference between ArrayList and LinkedList?


No. ArrayList LinkedList
1) ArrayList uses a dynamic array. LinkedList uses a doubly linked list.
ArrayList is not efficient for
2) manipulation because too much is LinkedList is efficient for manipulation.
required.
ArrayList is better to store and
3) LinkedList is better to manipulate data.
fetch data.
4) ArrayList provides random access. LinkedList does not provide random access.
LinkedList takes more memory overhead, as it
ArrayList takes less memory
5) stores the object as well as the address of
overhead as it stores only object
that object.

6) What is the difference between Iterator and ListIterator?


Iterator traverses the elements in the forward direction only whereas ListIterator
traverses the elements into forward and backward direction.
No. Iterator ListIterator

2|Page
The Iterator traverses the elements ListIterator traverses the elements in
1)
in the forward direction only. backward and forward directions both.
The Iterator can be used in List, Set,
2) ListIterator can be used in List only.
and Queue.
The Iterator can only perform ListIterator can perform ?add,? ?remove,?
3) remove operation while traversing and ?set? operation while traversing the
the collection. collection.

7) What is the difference between Iterator and Enumeration?


No. Iterator Enumeration
The Iterator can traverse legacy and Enumeration can traverse only legacy
1)
non-legacy elements. elements.
2) The Iterator is fail-fast. Enumeration is not fail-fast.
3) The Iterator is slower than Enumeration. Enumeration is faster than Iterator.
The Iterator can perform remove The Enumeration can perform only
4)
operation while traversing the collection. traverse operation on the collection.

8) What is the difference between List and Set?


The List and Set both extend the collection interface. However, there are some
differences between the both which are listed below.

o The List can contain duplicate elements whereas Set includes unique items.
o The List is an ordered collection which maintains the insertion order whereas
Set is an unordered collection which does not preserve the insertion order.
o The List interface contains a single legacy class which is Vector class whereas
Set interface does not have any legacy class.
o The List interface can allow n number of null values whereas Set interface only
allows a single null value.

9) What is the difference between HashSet and TreeSet?


The HashSet and TreeSet, both classes, implement Set interface. The differences
between the both are listed below.

o HashSet maintains no order whereas TreeSet maintains ascending order.


o HashSet impended by hash table whereas TreeSet implemented by a Tree
structure.
o HashSet performs faster than TreeSet.
o HashSet is backed by HashMap whereas TreeSet is backed by TreeMap.

10) What is the difference between Set and Map?


The differences between the Set and Map are given below.
3|Page
o Set contains values only whereas Map contains key and values both.
o Set contains unique values whereas Map can contain unique Keys with
duplicate values.
o Set holds a single number of null value whereas Map can include a single null
key with n number of null values.

11) What is the difference between HashSet and HashMap?


The differences between the HashSet and HashMap are listed below.

o HashSet contains only values whereas HashMap includes the entry (key,
value). HashSet can be iterated, but HashMap needs to convert into Set to be
iterated.
o HashSet implements Set interface whereas HashMap implements the Map
interface
o HashSet cannot have any duplicate value whereas HashMap can contain
duplicate values with unique keys.
o HashSet contains the only single number of null value whereas HashMap can
hold a single null key with n number of null values.

12) What is the difference between HashMap and TreeMap?


The differences between the HashMap and TreeMap are given below.

o HashMap maintains no order, but TreeMap maintains ascending order.


o HashMap is implemented by hash table whereas TreeMap is implemented by
a Tree structure.
o HashMap can be sorted by Key or value whereas TreeMap can be sorted by
Key.
o HashMap may contain a null key with multiple null values whereas TreeMap
cannot hold a null key but can have multiple null values.

13) What is the difference between HashMap and Hashtable?


No. HashMap Hashtable
1) HashMap is not synchronized. Hashtable is synchronized.
HashMap can contain one null key and Hashtable cannot contain any null key
2)
multiple null values. or null value.
HashMap is not ?thread-safe,? so it is Hashtable is thread-safe, and it can be
3)
useful for non-threaded applications. shared between various threads.
4) HashMap inherits the AbstractMap
4) Hashtable inherits the Dictionary class.
class

4|Page
14) What is the difference between Collection and Collections?
The differences between the Collection and Collections are given below.

o The Collection is an interface whereas Collections is a class.


o The Collection interface provides the standard functionality of data structure
to List, Set, and Queue. However, Collections class is to sort and synchronize
the collection elements.
o The Collection interface provides the methods that can be used for data
structure whereas Collections class provides the static methods which can be
used for various operation on a collection.

15) What is the difference between Comparable and


Comparator?
No. Comparable Comparator
Comparable provides only one sort of The Comparator provides multiple
1)
sequence. sorts of sequences.
It provides one method named
2) It provides one method named compareTo().
compare().
3) It is found in java.lang package. It is located in java.util package.
If we implement the Comparable interface,
4) The actual class is not changed.
The actual class is modified.

16) What do you understand by BlockingQueue?


BlockingQueue is an interface which extends the Queue interface. It provides
concurrency in the operations like retrieval, insertion, deletion. While retrieval of any
element, it waits for the queue to be non-empty. While storing the elements, it waits
for the available space. BlockingQueue cannot contain null elements, and
implementation of BlockingQueue is thread-safe.
Syntax:
public interface BlockingQueue<E> extends Queue <E>

17) What is the advantage of Properties file?


If you change the value in the properties file, you don't need to recompile the java
class. So, it makes the application easy to manage. It is used to store information
which is to be changed frequently. Consider the following example.

1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5. FileReader reader=new FileReader("db.properties");
6.

5|Page
7. Properties p=new Properties();
8. p.load(reader);
9.
10. System.out.println(p.getProperty("user"));
11. System.out.println(p.getProperty("password"));
12. }
13. }

Output
system
oracle

18) What does the hashCode() method?


The hashCode() method returns a hash code value (an integer number).
The hashCode() method returns the same integer number if two keys (by calling
equals() method) are identical.
However, it is possible that two hash code numbers can have different or the same
keys.
If two objects do not produce an equal result by using the equals() method, then the
hashcode() method will provide the different integer result for both the objects.

19) Why we override equals() method?


The equals method is used to check whether two objects are the same or not. It
needs to be overridden if we want to check the objects based on the property.
For example, Employee is a class that has 3 data members: id, name, and salary.
However, we want to check the equality of employee object by the salary. Then, we
need to override the equals() method.

20) How to synchronize List, Set and Map elements?


Yes, Collections class provides methods to make List, Set or Map elements as
synchronized:
public static List synchronizedList(List l){}
public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

21) What is the advantage of the generic collection?


There are three main advantages of using the generic collection.

o If we use the generic class, we don't need typecasting.


o It is type-safe and checked at compile time.

6|Page
o Generic confirms the stability of the code by making it bug detectable at
compile time.

22) What is hash-collision in Hashtable and how it is handled in


Java?
Two different keys with the same hash value are known as hash-collision. Two
separate entries will be kept in a single hash bucket to avoid the collision. There are
two ways to avoid hash-collision.

o Separate Chaining
o Open Addressing

23) What is the Dictionary class?


The Dictionary class provides the capability to store key-value pairs.

24) What is the default size of load factor in hashing based


collection?
The default size of load factor is 0.75. The default capacity is computed as initial
capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of
Map.

25) What do you understand by fail-fast?


The Iterator in java which immediately throws ConcurrentmodificationException, if
any structural modification occurs in, is called as a Fail-fast iterator. Fail-fats iterator
does not require any extra space in memory.

26) What is the difference between Array and ArrayList?


The main differences between the Array and ArrayList are given below.
SN Array ArrayList
The Array is of fixed size, means we ArrayList is not of the fixed size we can
1
cannot resize the array as per need. change the size dynamically.
2 Arrays are of the static type. ArrayList is of dynamic size.
Arrays can store primitive data types ArrayList cannot store the primitive data
3
as well as objects. types it can only store the objects.

27) What is the difference between the length of an Array and


size of ArrayList?
The length of an array can be obtained using the property of length whereas
ArrayList does not support length property, but we can use size() method to get the
number of objects in the list.
Finding the length of the array
7|Page
1. Int [] array = new int[4];
2. System.out.println("The size of the array is " + array.length);
3.

Finding the size of the ArrayList

1. ArrayList<String> list=new ArrayList<String>();


2. list.add("ankit");
3. list.add("nippun");
4. System.out.println(list.size());
5.

28) How to convert ArrayList to Array and Array to ArrayList?


We can convert an Array to ArrayList by using the asList() method of Arrays class.
asList() method is the static method of Arrays class and accepts the List object.
Consider the following syntax:
Arrays.asList(item)
We can convert an ArrayList to Array using toArray() method of the ArrayList class.
Consider the following syntax to convert the ArrayList to the List object.
List_object.toArray(new String[List_object.size()])

29) How to make Java ArrayList Read-Only?


We can obtain java ArrayList Read-only by calling the
Collections.unmodifiableCollection() method. When we define an ArrayList as Read-
only then we cannot perform any modification in the collection through add(),
remove() or set() method.

30) How to remove duplicates from ArrayList?


There are two ways to remove duplicates from the ArrayList.

o Using HashSet: By using HashSet we can remove the duplicate element from
the ArrayList, but it will not then preserve the insertion order.
o Using LinkedHashSet: We can also maintain the insertion order by using
LinkedHashSet instead of HashSet.

The Process to remove duplicate elements from ArrayList using the LinkedHashSet:

o Copy all the elements of ArrayList to LinkedHashSet.


o Empty the ArrayList using clear() method, which will remove all the elements
from the list.
o Now copy all the elements of LinkedHashset to ArrayList.

8|Page
31) How to reverse ArrayList?
To reverse an ArrayList, we can use reverse() method of Collections class. Consider
the following example.

1. import java.util.ArrayList;
2. import java.util.Collection;
3. import java.util.Collections;
4. import java.util.Iterator;
5. import java.util.List;
6. public class ReverseArrayList {
7. public static void main(String[] args) {
8. List list = new ArrayList<>();
9. list.add(10);
10. list.add(50);
11. list.add(30);
12. Iterator i = list.iterator();
13. System.out.println("printing the list....");
14. while(i.hasNext())
15. {
16. System.out.println(i.next());
17. }
18. Iterator i2 = list.iterator();
19. Collections.reverse(list);
20. System.out.println("printing list in reverse order....");
21. while(i2.hasNext())
22. {
23. System.out.println(i2.next());
24. }
25. }
26. }

Output
printing the list....
10
50
30
printing list in reverse order....
30
50
10

32) How to sort ArrayList in descending order?


To sort the ArrayList in descending order, we can use the reverseOrder method of
Collections class. Consider the following example.

9|Page
1. import java.util.ArrayList;
2. import java.util.Collection;
3. import java.util.Collections;
4. import java.util.Comparator;
5. import java.util.Iterator;
6. import java.util.List;
7.
8. public class ReverseArrayList {
9. public static void main(String[] args) {
10. List list = new ArrayList<>();
11. list.add(10);
12. list.add(50);
13. list.add(30);
14. list.add(60);
15. list.add(20);
16. list.add(90);
17.
18. Iterator i = list.iterator();
19. System.out.println("printing the list....");
20. while(i.hasNext())
21. {
22. System.out.println(i.next());
23. }
24.
25. Comparator cmp = Collections.reverseOrder();
26. Collections.sort(list,cmp);
27. System.out.println("printing list in descending order....");
28. Iterator i2 = list.iterator();
29. while(i2.hasNext())
30. {
31. System.out.println(i2.next());
32. }
33.
34. }
35. }

10 | P a g e
Output
printing the list....
10
50
30
60
20
90
printing list in descending order....
90
60
50
30
20
10

33) How to synchronize ArrayList?


We can synchronize ArrayList in two ways.

o Using Collections.synchronizedList() method


o Using CopyOnWriteArrayList<T>

34) When to use ArrayList and LinkedList?


LinkedLists are better to use for the update operations whereas ArrayLists are better
to use for the search operations.

11 | P a g e

You might also like