Collection interview questions

Q1. What is the Collection framework in Java?

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

Q2. 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:

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.

Arrays can only store homogeneous or similar type objects, but in Collection, heterogeneous objects can be stored.

Q3. Explain various interfaces used in the Collection framework?

The collection framework implements various interfaces, Collection interface and Map interface (java.util.Map) is the mainly used interfaces of the Java Collection Framework. A 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: The list interface extends the Collection interface, and it is an ordered collection of objects. It contains duplicate elements. It also allows random access to elements.

Syntax:

public interface List<E> extends Collection<E>  

3. Set interface: Set (java.util.Set) interface is a collection that cannot contain duplicate elements. It can only include inherited methods of the Collection interface.

Syntax:

public interface Set<E> extends Collection<E>

4. Queue interface: Queue (java.util.Queue) interface defines the queue data structure, which stores the elements in the form FIFO (first in first out).

Syntax:

public interface Queue<E> extends Collection<E>  

5. 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>  

6. 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 that implement Map in java that are Map interface and Sorted Map.

Q4. What is the difference between ArrayList and Vector?

ArrayListVector
ArrayList is not synchronized.The vector is synchronized.
ArrayList is not a legacy class.Vector is a legacy class.
ArrayList increases its size by 50% of the array size.Vector increases its size by doubling the array size.
ArrayList is not thread-safe as it is not synchronized.Vector list is thread-safe as it's every method is synchronized.


Q5. What is the difference between ArrayList and LinkedList?

Below are some of the differences in ArrayList and LinkedList

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

Q6. How to measure the performance of an ArrayList?

The performance of ArrayList can be measured by:

Adding an element: We can add an element at the end of ArrayList using add(E e) method. It is O(1). In the worst scenario, it might go to O(n). 

Retrieving an element: We can access the array index using get(int index). The performance, in this case, can be measured using ArrayList get() is O(1).

Removing an element: In case, if the developers are removing an element using the remove(int index), then the performance of ArrayList can be calculated using said remove(int index) operation in the O(n – index) method.

Q7. What is the difference between Iterator and ListIterator?

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

IteratorListIterator
The Iterator traverses the elements in the forward direction only. ListIterator traverses the elements in backward and forward directions both.
The Iterator can be used in List, Set, and Queue.ListIterator can be used in List only.
The Iterator can only perform remove operation while traversing the collection.ListIterator can perform add, remove, and set operation while traversing the collection.


Q8. Explain Linkedhashmap

LinkedHashMap is the implementation of the Map interface. It can also extend the HashMap class. Therefore, like HashMap, LinkedHashMap enables Java developers to allow one null key and more than one null value.

Q9. What is the difference between an Iterator and an Enumeration?

IteratorEnumeration
The Iterator can traverse legacy and non-legacy elements.Enumeration can traverse only legacy elements.
The Iterator is fail-fast.Enumeration is not fail-fast.
The Iterator is slower than Enumeration.Enumeration is faster than Iterator.
The Iterator can perform a remove operation while traversing the collection.The Enumeration can perform only traverse operation on the collection.


Q10. Explain RandomAccess interface

RandomAccess interface is used by List implementations for the indication that they are supporting fast. The primary purpose of this interface is to allow generic algorithms to alter their behavior to provide good performance when applied to either random or sequential access lists.

Q11. What is the difference between a List and a Set?

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

The List can contain duplicate elements whereas the Set includes unique items.

The List is an ordered collection that maintains the insertion order whereas the Set is an unordered collection that does not preserve the insertion order.

The List interface can allow n number of null values whereas the Set interface only allows a single null value.

Q12. Explain diamond operator

The diamond operator enables the compiler to collect the type arguments of a generic class. In Java SE, we can substitute the parameterized constructor with an empty parameter set (<>) known as the diamond operator.

Q13. What is the difference between HashSet and TreeSet?

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

HashSet maintains no order whereas TreeSet maintains ascending order.

HashSet is impended by a hash table whereas TreeSet is implemented by a Tree structure.

HashSet performs faster than TreeSet.

HashSet is backed by HashMap whereas TreeSet is backed by TreeMap.

Q14. What is the difference between Set and Map?

The differences between the Set and Map are given below.

Set contains values only whereas Map contains key and values both.

Set contains unique values whereas Map can contain unique Keys with duplicate values.

Set holds a single number of null values whereas Map can include a single null key with n number of null values.

Q15. How to iterate a map?

The developer cannot directly iterate the map, but, this interface has two methods that give a view set of the map. These methods are:

Set<Map.Entry<K, V>>entrySet(): It is a method that returns a set having the entries mentioned in the map. These entries are generally objected, which has type Map. Entry.

Set<K>keySet(): This Java method returns a set that has the map key.

Q16. What is the difference between HashSet and HashMap?

The differences between HashSet and HashMap are listed below.

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.

HashSet implements the Set interface whereas HashMap implements the Map interface

HashSet cannot have any duplicate value whereas HashMap can contain duplicate values with unique keys.

HashSet contains only a single number of null values whereas HashMap can hold a single null key with n number of null values.

Q17. What is the difference between HashMap and TreeMap?

The differences between HashMap and TreeMap are given below.

HashMap maintains no order, but TreeMap maintains ascending order.

HashMap is implemented by a hash table whereas TreeMap is implemented by a Tree structure.

HashMap can be sorted by Key or value whereas TreeMap can be sorted by Key.

HashMap may contain a null key with multiple null values whereas TreeMap cannot hold a null key but can have multiple null values.

Q18. What is the difference between HashMap and Hashtable?

HashMapHashtable
HashMap is not synchronizedHashtable is synchronized.
HashMap can contain one null key and multiple null values.Hashtable cannot contain any null key or null value.
HashMap is not  thread-safe, so it is useful for non-threaded applications. Hashtable is thread-safe, and it can be shared between various threads.
HashMap inherits the AbstractMap classHashtable inherits the Dictionary class.


Q19. What is the difference between Collection and Collections?

The differences between the Collection and Collections are given below.

The Collection is an interface whereas Collections is a class.

The Collection interface provides the standard functionality of data structure to List, Set, and Queue. However, the Collections class is to sort and synchronize the collection elements.

The Collection interface provides the methods that can be used for data structure whereas the Collections class provides the static methods which can be used for various operations on a collection.

Q20. What is the difference between Comparable and Comparator?

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


Q21. What do you understand by BlockingQueue?

BlockingQueue is an interface that extends the Queue interface. It provides concurrency in the operations like retrieval, insertion, and 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 the implementation of BlockingQueue is thread-safe.

Syntax:

public interface BlockingQueue<E> extends Queue <E>

Q21. 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 the 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 a different integer results for both objects.

Q22. Why do we override the 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.

Q23. How to synchronize List, Set, and Map elements?

Yes, the Collections class provides methods to make List, Set, or Map elements 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){}

Q24. What is the advantage of the generic collection?

There are three main advantages of using the generic collection.

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

It is type-safe and checked at compile time.

Generic confirms the stability of the code by making it bug detectable at compile time.

Q25. 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 collision. There are two ways to avoid hash-collision.

Separate Chaining

Open Addressing

Q26. What is the Dictionary class?

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

Q27. What is the default size of load factor in hashing-based collection?

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

Q28. What do you understand by fail-fast?

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

Q29. What is the difference between Array and ArrayList?

The main differences between the Array and ArrayList are given below.

ArrayArrayList
The Array is of fixed size, means we cannot resize the array as per need.ArrayList is not of the fixed size we can change the size dynamically.
Arrays are of the static type.ArrayList is of dynamic size.
Arrays can store primitive data types as well as objects.ArrayList cannot store the primitive data types it can only store the objects.


Q30. What is the difference between the length of an Array and the size of an ArrayList?

The length of an array can be obtained using the property of length whereas ArrayList does not support the length property, but we can use the size() method to get the number of objects in the list.

Finding the length of the array

Int [] array = new int[10];  

System.out.println("The size of the array is " + array.length);  

Finding the size of the ArrayList

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

list.add("Hello");    

list.add("Java");  

list.add("Program"); 

System.out.println(list.size());

Q31. How to convert ArrayList to Array and Array to ArrayList?

We can convert an Array to an ArrayList by using the asList() method of the Arrays class. asList() method is the static method of the Arrays class and accepts the List object. Consider the following syntax:

Arrays.asList(item)  

We can convert an ArrayList to Array using the toArray() method of the ArrayList class. Consider the following syntax to convert the ArrayList to the List object.

objctt.toArray(new String[List_object.size()])

Q33. 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.

Q34. How to synchronize ArrayList?

We can synchronize ArrayList in two ways.

Using Collections.synchronizedList() method

Using CopyOnWriteArrayList<T>

Q35. When to use ArrayList and LinkedList?

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


Exception Handling Interview Questions

DBMS Interview Questions Set -1

DBMS Interview Questions Set -2

SQL Interview Question Set -1

SQL Interview Question Set -2

JPA Interview Questions Set -1

JPA Interview Question Set -2

Hibernate Interview Questions

Spring Boot Interview Questions Set 1

Spring Boot Interview Questions Set 2

GIT Interview Questions

Redis Interview Questions

Core Java Interview Questions Set -1

Docker interview question Set -1

Docker interview question Set -2

Kubernetes Interview Question Set -1

Kubernetes Interview Question Set -2

Collection interview questions

Kafka Interview Questions

No comments:

Post a Comment