[go: up one dir, main page]

0% found this document useful (0 votes)
23 views51 pages

Collection Interview Questions

Uploaded by

Binod Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views51 pages

Collection Interview Questions

Uploaded by

Binod Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Top 50 Collection Framework FAQ’s

Q - 1) What is Collection in Java?

• In Java, a collection is a framework that provides an


architecture for storing and manipulating a collection
of objects.
• Collections in Java are capable of doing any data
operations such as searching, sorting, insertion,
manipulation, and deletion.
Q - 2) Differentiate between Collection and collections in the context of Java.

Collection Collections
It's used to represent a collection of It defines a number of useful methods for
separate objects as a single entity. working with collections.
It is an interface. It is a utility class.
Since Java 8, the Collection is an interface
with a static function.
It only has static methods in it.
Abstract and default methods can also be
found in the Interface.
Q - 3) Why Map is not inherited from Collection
interface although it is a part of Java collection
framework?

• Map is a collection of key-value pairs where as other


collection types like List, Set and Queue are the
collection of values.
• Collection interface has the methods which support
only the collection of values but not the collection of
key-value pairs.
Q - 4) Differentiate between List and Set in Java.

Set List
It is an unordered sequence. It is an ordered sequence.

Duplicate elements are not permitted in


Duplicate elements are allowed in the list
Set.

Access to items from a certain position is Elements can be accessed based on their
not permitted. position.

It is possible to store several null


A null element can only be stored once.
elements.
Q-5) What are the characteristics of sets?

• Set contains only unique elements.


• It does not allow duplicates.
• Set can have maximum one null element.
• Random access of elements is not possible.
• Order of elements in a set is implementation
dependent.
Q - 6) Differentiate between Iterator and ListIterator in Java.

Iterator ListIterator
Only has the ability to traverse In both forward and backward
components in a Collection in a forward orientations, can traverse components in
direction. a Collection.
It offers methods to get element indexes
Iterators cannot be used to obtain
at any time while traversing List, such as
indexes.
next Index() and previous Index().
It aids in the traversal of Maps, Lists, and Only List may be traversed, not the other
Sets. two.
It throws a Concurrent Modification At any time, you can quickly add elements
Exception since it can't add elements. to a collection.
next(), previous(), has Next(), has
next(), remove(), and has Next are some
Previous(), and add() are some of the List
of the Iterator's functions ().
Iterator's methods
Q - 7) 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.
Q - 8) What is the difference between HashMap and Hashtable?

HashMap Hashtable

HashMap is not synchronized. Hashtable is synchronized.

HashMap can contain one null key and Hashtable cannot contain any null key or
multiple null values. null value.

HashMap is not ?thread-safe,? so it is Hashtable is thread-safe, and it can be


useful for non-threaded applications. shared between various threads.

HashMap inherits the AbstractMap class Hashtable inherits the Dictionary class.
Q - 9) 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.
Q - 10) What is difference between Array and ArrayList

Array ArrayList

The Array is of fixed size, means ArrayList is not of the fixed size
we cannot resize the array as we can change the size
per need. dynamically.
Arrays are of the static type. ArrayList is of dynamic size.

Arrays can store primitive data ArrayList cannot store the


types as well as objects. primitive data types it can only
store the objects.
Q - 11) How to convert ArrayList to Array and Array to ArrayList in java?

• We can convert an Array to ArrayList by using the


asList() method of Arrays class.
-Syntax: Arrays.asList(item)
• We can convert an ArrayList to Array using toArray()
method of the ArrayList class.
-Syntax :
-List_obj.toArray(new String[List_obj.size()])
Q - 12) How to remove duplicates from ArrayList in Java?

• To remove duplicates from ArrayList, we can


convert it into Set like below:
Q - 13) What is difference between ArrayList and Vector?

ArrayList Vector

ArrayList is not Synchronized The vector is synchronized.

The size of ArrayList is incremented up to The size of ArrayList is incremented up to


50% of the current array size if the 100% of the current array size if the
number of elements exceeds its capacity. number of elements exceeds its capacity.

ArrayList is fast because it is non- Vector is slower because it’s


Synchronized. synchronized.

The iterator interface is used to traverse An iterator interface or Enumeration can


the elements be used to traverse the vector.
Q - 14) What is a priority queue in Java?
• In this queue, a high priority element is served before
a low priority element irrespective of their insertion
order.
Q - 15) What is Set in Java Collections framework and list down its
various implementations?

• A Set refers to a collection that cannot contain


duplicate elements.
• Set implementations which are:
-HashSet
-TreeSet
-LinkedHashSet
Q - 16) Can you add a null element into a TreeSet or HashSet?

• In HashSet, only one null element can be added but


in TreeSet it can’t be added as it makes use of
NavigableMap for storing the elements.
Q - 17) Differentiate between Set and Map.

Set Map
Belongs to java.util package Belongs to java.util package
Extends the Collection interface Doesn’t extend the Collection interface
Duplicate keys are not allowed but
Duplicate values are not allowed
duplicate values are
Only one null key can be stored but
Only one null values can be stored
multiple null values are allowed
Doesn’t maintain any insertion order Doesn’t maintain any insertion order
Q - 18) Differentiate between HashSet and HashMap.

HashSet HasMap
Based on Set implementation Based on Map implementation
Doesn’t allow any duplicate keys but
Doesn’t allow any duplicate elements
duplicate values are allowed
Allows only one null key but any number
Allows only a single null value
of null values
Has slower processing time Has faster processing time
Uses HashMap as an underlying data Uses various hashing techniques for data
structure manipulation
Q - 19) Differentiate between HashSet and TreeSet.

HashSet TreeSet
Uses HasMap to store elements Uses Treemap to store elements
By default, it stores elements in their
It is unordered in nature
natural ordering
Has faster processing time Has slower processing time
Uses hasCode() and equals() for Uses compare() and compareTo() for
comparing comparing
Allows only one null element Doesn’t allow any null element
Takes up less memory space Takes up more memory space
Q - 20) Write a program to sort ArrayList in
descending order?
• To sort the ArrayList in descending order we will use
two methods Collections.reverseOrder() method and
Collections.sort() method.
Q - 21) Write a program to convert HashSet to
Array?
Q - 22) 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.
• Interfaces are List , Set , Map , Queue , Dequeue.
Q - 23) What is the difference between Iterator
and Enumeration?

Iterator Enumeration

The Iterator can traverse legacy and Enumeration can traverse only legacy
non-legacy elements. 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 remove The Enumeration can perform only
operation while traversing the traverse operation on the collection.
collection.
Q - 24) 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.
Q - 25) What is the difference between HashMap and TreeMap?

HashMap TreeMap
HashMap does not keep track of the TreeMap preserves insertion order.
order of insertions.

Map, Cloneable, and Serializable TreeMap is capable of being Cloned


interfaces are all ones that are and Serialized, in addition to
implemented by HashMap. implementing the NavigableMap
interface.

The Null key can be used once in TreeMap does not let the use of a null
HashMap, and the Null value can be key, but it does permit the use of a null
used any number of times. value any number of times.
Q - 26) What is the difference between ArrayList
and LinkedList?
ArrayList LinkedList
The elements of this class are stored in a The elements of this class are stored in a
dynamic array. doubly-linked list.
The List and Deque interfaces are both
The List interface is implemented by this
implemented by this class. As a result, it
class. As a result, this serves as a list.
can be used as both a list and a deque.
Because there is no concept of changing
Because of the internal implementation, memory bits in a doubly-linked list,
manipulating an ArrayList takes longer. manipulating it takes less time than
manipulating an ArrayList
This class is more useful when the
This class is more useful when the
application requires data storage and
application requires data manipulation.
access.
Q - 27) When would you prefer TreeSet to HashSet?

• TreeSet returns a sorted list that is always in


ascending order.
• The locality of TreeSet is higher than that of HashSet.
• TreeSet is a fantastic solution if you need to do
read/write operations regularly.
Q - 28) Can you add a null element into a TreeSet or HashSet?

• We can add null elements in a HashSet but we


cannot add null elements in a TreeSet.
Q-29)How can you make an ArrayList read-only in Java?

• With the help ofCollections.unmodifiableList()


method, we can easily make an ArrayList read-only.
Q - 30) Differentiate between Q-Comparable and Comparator in the context of Java.

Comparable Comparator
Multiple sorting sequences are available
A single sorting sequence is provided by
in the Comparator. To put it another way,
Comparable. To put it another way, we
we can sort the collection based on
can sort the collection by a single
different criteria such as id, name, and
attribute such as id, name, or price.
price.
To sort elements, Comparable provides To order elements, the Comparator
the compareTo() method. provides the compare() method.
It is present in the java.lang package. It is present in the java.util package.
The original class is unaffected by the
The original class is affected by
comparator, i.e. the real class is
Comparable, i.e. the real class is changed.
unaffected.
The Collections.sort(List) method can be The Collections.sort(List, Comparator)
used to sort Comparable type list method can be used to sort the list
members. components of the Comparator type.
Q - 31) Explain fail-fast and fail-safe iterators.

• If the collection's structure is changed, Fail-


Fast iterators immediately throw
ConcurrentModificationException.
• Fail-safe Iterator classes include ArrayList Iterator
and HashMap Iterator.
• If a collection is structurally updated while iterating
over it, fail-safe iterators don't throw any
exceptions.
• Fail-safe Iterators include the CopyOnWriteArrayList
and ConcurrentHashMap classes.
Q - 32) Differentiate between Fail-Fast and Fail-
Safe?

Fail-Fast Fail-Safe
These types of iterators do not allow
These types of iterators allow modifying
modifying the collection while iterating
the collection while iterating over it.
over it.
It throws
ConcurrentModificationException if the No exception is thrown if the collection is
collection is modified while iterating over modified while iterating over it.
it.
It uses the original collection while It uses a copy of the original collection
traversing the elements. while traversing over it.
No extra memory is required in this case. Extra memory is required in this case.
Q - 33) Why does HashMap allow null whereas HashTable does not allow null?

• The objects used as keys must implement the


hashCode and equals methods in order to
successfully save and retrieve objects from a
HashTable.
• These methods cannot be implemented by null
because it is not an object.
• HashMap is a more advanced and improved variant
of Hashtable.
Q - 34) Why do we need synchronized ArrayList when we have Vectors (which are synchronized) in Java?

• Vector is slightly slower than ArrayList due to


the fact that it is synchronized and thread-safe.
• Vector's functionality is that it synchronizes each
individual action.
• Vector also synchronizes on a per-operation
basis, which is almost never done.
Q - 35) Why does not the Map interface extend the Collection Interface or vice-versa?

• If Map extends the Collection Interface, "Key-value


pairs" can be the only element type for this type of
Collection.
• You can't inquire what value a specific key
corresponds to, and you can't delete an entry
without knowing what value it corresponds to.
Q - 36) Write a program in Java to display the contents of a HashTable using enumeration.

• We use the hasMoreElements and the nextElement


methods of the Enumeration class to iterate through
the HashTable.
Q - 37) Write a program to shuffle all the
elements of a collection in Java.
• We use the shuffle() method of the Collections
class.
Q - 38) Write a program in java to get the collection view of the values from HashMap.

• We use the values() function of the HashMap to get


the collection view.
Q - 39) What is the difference between Array and Collection in Java?

Arrays Collection

Arrays are fixed in size that is once we The collection is growable in nature and is
create an array we can not increase or based on our requirements. We can
decrease based on our requirements. increase or decrease of size.

With respect to memory, Arrays are not With respect to memory, collections are
recommended for use. recommended for use.

With respect to performance, Arrays are With respect to performance, collections


recommended for use. are not recommended for use.

Arrays can hold only homogeneous data Collection can hold both homogeneous
types elements. and heterogeneous elements.
Q- 40) Why iterator in hashmap is considered fail-fast?

• The fail-fast feature ensures that the iterator


fails immediately if it detects that any
modification of the collection will lead to
anomalous behavior in the future.
Q - 41) How TreeMap works in Java?

• TreeMap stores the key-value pairs, but TreeMap


sorts the keys ascending rather than descending like
HashMap.
• In TreeMap, the elements are sorted based on a Red-
Black tree.
• A red-black tree is a self-balancing binary search tree
where each node has an extra bit, and that bit is
often interpreted as the color (red or black).
Q - 42) What will happen if two different keys of HashMap return the same hashcode()?

• When two different keys of HashMap return


the same hash code, they will end up in the
same bucket; therefore, collisions will occur.
Q - 43) How can you synchronize an ArrayList in Java?

• Using the Collections.synchronizedList()


method. We can synchronize our collections in
Java.
Q - 44) Write a program to iterate the list using the lambda expression.

• Iteration can be done using a lambda


expression.
Q - 45) What is the default size of the load factor in the hashing-based collection?

• The default load factor size is 0.75. The default


capacity is calculated by multiplying the initial
capacity by the load factor.
Q - 46) Write a program to convert a given array
into a collection with the asList() method.
• To convert array-based data into Collection based we
can use java.util.Arrays class.
• This class provides a static method asList.
Q - 47) What are the features of Java Hashmap?

• It allows us to store the null keys as well, but there


should be only one null key object and there can be
any number of null values.
• This class makes no guarantees as to the order of the
map.
• To use this class and its methods, you need to
import java.util. HashMap package or its superclass.
• Syntax: public class HashMap<K,V> extends
AbstractMap<K,V> implements Map<K,V>, Cloneable,
Serializable
Q - 48) What is the hashCode()?

• It is defined in the Java Object class which computes


the hash values of given input objects.
• Hashcode value is mostly used in hashing-based
collections like HashMap, HashSet, HashTable.
• Syntax : public int hashCode()
Q - 49) What is BlockingQueue in Java?

• The BlockingQueue interface in Java is added in Java


1.5 along with various other concurrent Utility
classes like ConcurrentHashMap, Counting
Semaphore, CopyOnWriteArrrayList, etc.
• The BlockingQueue interface supports flow control
by introducing blocking if either BlockingQueue is full
or empty.
• If we try to enqueue the null item, then it throws
NullPointerException.
Q - 50) What is the difference between Queue and Stack?

Stack Queue

Stacks works on the LIFO principle, which Queues work on the FIFO principle, which
means that the element inserted at the last will means that the element inserted first will be
be the first element that will be taken out. the first element that will be taken out.

In queues, insertion occurs at the rear of the


In stacks, insertion, and deletions take place list and deletion takes place from the front of
only from the top. the list.

Insert operation is called push operation. Insert operation is called enqueue operation.

Delete operation is called pop operation. Delete operation is called dequeue operation.

Two pointers are maintained for accessing


The top of a stack always points to the last queues. The front pointer points to the first
element in the list, which is the only pointer inserted element, and the rear pointer points
used to access the list. to the last inserted element.

You might also like