1) What is the Collection framework in Java?
A Collection Framework is a combination of classes and interfaces that 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. This framework offers an efficient and
flexible method of handling data structures by providing a standardised approach
to working with collections of items.
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:
Aspect Array Collection
Size Fixed size Dynamically (resizable)
Type of elements Homogeneous (same Heterogeneous (different
type) types)
Methods Limited methods Abundance of methods
available for manipulation and
iteration
Flexibility Limited flexibility High flexibility for
manipulation and
expansion
Usage Basic data storage Advanced data
manipulation and storage
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:
This is the collection hierarchy's base interface. Its elements are a collection of
items that it represents. Duplicate elements may be found in collections, and
elemental orders may change. Commonly used classes like ArrayList, LinkedList,
and HashSet are examples of implementations of this interface.
Syntax:
public interface Collection<E>extends Iterable
Where <E> represents that this interface is of Generic type
2. List interface:
The list extends the Collection interface and represents an ordered collection of
elements. It allows duplicate elements and provides methods to access
elements by their index. Implementations of the List interface include ArrayList,
LinkedList, and Vector.
Syntax:
public interface List<E> extends Collection<E>
3. Set interface:
A collection that is incapable of having duplicate elements is represented by a
set, which expands on the Collection interface. It does not ensure the
components' order; instead, it simulates the abstraction of a mathematical set.
HashSet, TreeSet, and LinkedHashSet implement the Set interface.
Syntax:
public interface Set<E> extends Collection<E>
4. Queue interface:
A queue is a collection intended to keep things before they are processed, and it
extends the Collection interface. Its elements are arranged in FIFO
(First-In-First-Out) order. The Queue interface is implemented by LinkedList,
PriorityQueue, and ArrayDeque.
Syntax:
public interface Queue<E> extends Collection<E>
5. Deque Interface
Deque stands for "Double Ended Queue" and extends the Queue interface. It
represents a linear collection that supports element insertion and removal at
both ends. Deques can function as standard queues (FIFO) as well as stacks
(LIFO). Implementations of the Deque interface include LinkedList and
ArrayDeque.
Syntax:
public interface Dequeue<E> extends Queue<E>
5. Map interface:
The Map interface does not extend the Collection interface, in contrast to other
collection interfaces. It shows a mapping of keys to values in which a single
value is connected to each key. HashMap, TreeMap, and LinkedHashMap are
examples of map implementations. Furthermore, a map that retains its keys in
ascending order is provided by the SortedMap interface, which extends Map.
Syntax
public interface Map<K, V> {}
4) What are the difference between ArrayList and Vector?
Aspect ArrayList Vector
Synchronization ArrayList is not Vector is synchronized.
synchronized.
Legacy ArrayList is not a legacy Vector is a legacy class.
class.
Resize Strategy ArrayList increases its Vector increases its size
size by 50% of the array by doubling the array size.
size.
Thread Safety ArrayList is not Vector list is
?thread-safe? as it is not ?thread-safe? as it?s
synchronized. every method is
synchronized.
Performance Generally faster due to Slower due to
lack of synchronization synchronization
overhead. overhead.
Iterator Fail-fast iterator (Throws Fail-safe iterator (Doesn't
ConcurrentModificationEx throw
ception if modified during ConcurrentModificationEx
iteration). ception if modified during
iteration).
Usage Preferred in Used in legacy or
non-concurrent concurrent environments.
environments.
5) What are the difference between ArrayList and LinkedList?
Aspect ArrayList LinkedList
Data Structure ArrayList uses a dynamic LinkedList uses a doubly
array. linked list.
Efficiency ArrayList is not efficient LinkedList is efficient for
for manipulation because manipulation.
too much is required.
Data Storage ArrayList is better to store LinkedList is better to
and fetch data. manipulate data.
Access ArrayList provides LinkedList does not
random access. provide random access.
Memory Overhead ArrayList takes less LinkedList takes more
memory overhead as it memory overhead, as it
stores only object stores the object as well
as the address of that
object.
6) What are the differences between Iterator and
ListIterator?
Iterator traverses the elements in the forward direction only whereas ListIterator
traverses the elements into forward and backward direction.
Aspect Iterator ListIterator
Traversal Direction The Iterator traverses the ListIterator traverses the
elements in the forward elements in backward
direction only. and forward directions
both.
Applicable Collections The Iterator can be used ListIterator can be used in
in List, Set, and Queue. List only.
Supported Operations The Iterator can only ListIterator can perform
perform remove operation add, remove, and set
while traversing the operation while traversing
collection. the collection.
Current Position It does not maintain a It maintains a current
Management current position pointer position pointer.
Modification of Collection It cannot add or modify It can add, remove, or
elements during traversal. modify elements during
traversal.
Implementation Classes java.util.Iterator java.util.ListIterator
7) What are the differences between Iterator and
Enumeration?
Aspect Iterator Enumeration
Traversal Capability The Iterator can traverse Enumeration can traverse
legacy and non-legacy only legacy elements.
elements.
Fail-Fast Behavior The Iterator is fail-fast. Enumeration is not
fail-fast.
Speed The Iterator is slower than Enumeration is faster
Enumeration. than Iterator.
Modification of Collection The Iterator can perform The Enumeration can
remove operation while perform only traverse
traversing the collection. operation on the
collection.
Current Position It maintains a current It does not maintain a
Management position pointer current position pointer
Support for Collection List, Set, Queue, Map Mainly supports legacy
Types collection classes like
Vector, Hashtable, and
Properties.
Concurrent Modification Detects No built-in mechanism for
concurrent modification. detecting modifications.
Methods It has additional methods It has methods like
like hasNext(), next(). hasMoreElements(),
nextElement().
8) What are the differences between List and Set?
Comparison Point List Set
Duplication of Elements It can contain duplicate It includes only unique
elements. items.
Ordering of Elements It maintains insertion It does not preserve
order. insertion order.
Legacy Classes It contains legacy class It does not have any
Vector. legacy class.
Null Values It can allow multiple null It allows a single null
values. value.
Subinterfaces It includes ListIterator, It includes SortedSet,
ListIterator. NavigableSet.
Example Classes ArrayList, LinkedList, HashSet, TreeSet.
Vector.
9) What are the differences between HashSet and TreeSet?
Aspect HashSet TreeSet
Ordering of Elements Maintains no specific Maintains elements in
order ascending order
Implementation Structure Implemented using a Implemented using a tree
hash table structure
Performance Generally faster due to Slightly slower due to
constant-time operations log(n) time operations
Backing Data Structure Backed by a HashMap Backed by a TreeMap
Ordering of Elements Unordered Ordered
10) What are the differences between Set and Map?
Aspect Set Map
Elements It contains only values. It contains key-value
pairs.
Uniqueness of Elements It contains unique values. It can contain unique keys
with duplicate values.
Handling of Null Values It can hold a single null It can have a single null
value. key with multiple null
values.
Accessing Elements It is accessed by iteration It is accessed by keys.
or specific methods.
Examples HashSet, TreeSet, HashMap, TreeMap,
LinkedHashSet LinkedHashMap
11) What are the differences between HashSet and
HashMap?
Aspect HashSet HashMap
Elements It contains only values. It contains key-value
pairs.
Interface Implementation It implements Set It implements Map
interface. interface.
Iteration It can be directly iterated It needs to be converted
into Set for iteration
Uniqueness of Elements It cannot have duplicate It can contain duplicate
values. values with unique keys.
Handling of Null Values It can hold a single null It can have a single null
value. key with multiple null
values.
Internal Data Structure It implements using a It implements using an
hash table. array of buckets (hash
table and linked list).
12) What are the differences between HashMap and
TreeMap?
Aspect HashMap TreeMap
Ordering of Elements There is no specific order. It maintains elements in
ascending order
Implementation Structure It implements using a It implements using a tree
hash table. structure
Sorting Capability It can be sorted by key or It can be sorted by key
value. only.
Null Key Handling It can contain a null key It cannot have a null key
with multiple null values. but can have multiple null
values.
Internal Data Structure It uses hash table for It uses a red-black tree for
storage and retrieval. storage and retrieval.
13) What are the differences between HashMap and
Hashtable?
Aspect HashMap Hashtable
Synchronization It is not synchronized. It is synchronized.
Null Key and Value It can have one null key It cannot have null keys or
Handling and multiple null values. values.
Thread Safety It is not thread-safe. It is Tthread-safe.
Inheritance It inherits AbstractMap It inherits Dictionary
class. class.
Performance It generally offers better It may have performance
performance. overhead due to
synchronization.
Iteration Behavior Order of iteration may not Iteration occurs in the
be predictable order of insertion
Iterator Fail-Safety It is fail-fast iterator. It is fail-safe iterator.
14) What are the differences between Collection and
Collections?
Aspect Collection Collections
Type It is an interface. It is a class.
Purpose It defines a standard It provides utility methods
functionality for data for sorting and
structures like List, Set, synchronizing collections.
and Queue.
Methods It defines methods for It provides static methods
data structure for various collection
manipulation. operations.
Example Implementations ArrayList, LinkedList, Collections.sort(),
HashSet Collections.synchronized
List()
Nullability It can contain null It does not have any
elements. direct impact on
nullability.
Extensibility It can be implemented by It cannot be extended or
other interfaces and implemented.
classes.
15) What are the differences between Comparable and
Comparator?
Aspect Comparable Comparator
Sort Sequences It provides one sort It provides multiple sort
sequence. sequences.
Method It requires implementing It requires implementing
compareTo() method. compare() method.
Location It belongs to java.lang It belongs to java.util
package. package.
Class Change It modifies the actual It does not modify the
class. actual class.
Flexibility It is less flexible as it's It is more flexible, allows
tied to the object's class sorting based on different
criteria
16) What do you understand by BlockingQueue?
BlockingQueue is an interface that extends the Queue interface. It provides
concurrency in operations like retrieval, insertion, and deletion. When retrieving
an element, it waits for the queue to be non-empty. When storing elements, it
waits for available space. BlockingQueue cannot contain null elements, and its
implementation is thread-safe.
It's crucial to remember that null components are not allowed in BlockingQueue
implementations. These implementations are also thread-safe, which makes
them appropriate in situations where several threads must concurrently access
and change a shared queue. In concurrent programming, BlockingQueue is
frequently used to manage data interchange between producer and consumer
threads in a thread-safe way.
Syntax:
public interface BlockingQueue<E> extends Queue <E>
17) What is the advantage of Properties file?
If we change the value in the properties file, we do not need to recompile the Java
class. So, it makes the application easy to manage. It is used to store information
that is to be changed frequently. Consider the following example.
Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
Output
Tpointtech 12345
Explanation
The snippet of code that is provided loads the key-value pairs that indicate
configuration settings from the db.properties file using the Properties class. The
values linked to certain keys ("user" and "password") are then retrieved from the
properties file using the getProperty() method, and they are subsequently shown
on the console. By separating the configuration data from the application logic,
this method facilitates flexibility and manageability.
db.properties
user= Tpointtech
password=12345
18) What does the hashCode() method?
Java's hashCode() function yields the object's hash code value. Many data
structures, including HashMap, HashSet, and others, employ this value to
organise and store things efficiently. The hashCode() method's main goal is to
give an object's state a distinct integer representation.
1. Separate objects can share the same hash code, even if the hashCode()
method seeks to generate unique hash codes for each object.
2. Two objects may not always generate the same hash code even if their
equals() function indicates that they are equal. For consistency's sake, two
objects should share the same hash code if the equals() method
determines that they are equal.
3. The equals () function and the hashCode () technique are usually used
together. To preserve consistency, it is advised that classes that override
the equals() method also override the hashCode() function. This
guarantees that items of the same kind have the same hash code, which is
necessary for some data structures to function effectively.
4. Java's Object class provides the default implementation of the hashCode()
method, that produces hash codes depending on the object's memory
location. To offer a more meaningful hash code based on the object's
state, user-defined classes typically override this function.
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.
@Override
public boolean equals(Object obj) {
// Check if the object being compared is the same instance
if (this == obj) {
return true;
}
// Check if the object being compared is null or of a different class
if (obj == null || getClass() != obj.getClass()) {
return false;
}
// Convert the object to the same class type
Employee other = (Employee) obj;
// Compare the properties for equality
return this.salary == other.salary; // Example: Compare based on salary
}
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)
These methods provide thread-safe collection operations by enclosing the
supplied collection (List, Set, or Map) in a synchronised wrapper. This avoids
dangerous race circumstances and ensures data integrity, especially in situations
where multiple threads may access or modify the collection concurrently.
21) What are the advantages of the generic collection?
Generic collections in Java provide several advantages over non-generic
collections:
1. Elimination of Type Casting
A major benefit of utilising generic collections is not requiring explicit type
casting. When retrieving elements from non-generic collections, we must cast
them to the correct data type; if this is done incorrectly, runtime issues may
result. By using generics, we can work directly with the proper data type without
casting because the compiler guarantees type safety at compilation time.
2. Type Safety
The compiler guarantees that only the proper data types are utilised within the
collection by using generic collections, that offer type safety. By doing this,
runtime issues caused by mismatched data types are avoided. When
constructing a generic collection, we can reduce the possibility of errors resulting
from erroneous data types by clearly defining the types of components that the
collection can include by using the type argument.
3. Compile-Time Checking:
Compile-time checking is an additional benefit of generic collections. Type
checks and problems relating to types can be found by the compiler prior to code
execution because the type information is available at compile time. This
enhances code stability and reliability by spotting any flaws early in the
development process. Coders can lessen the chance of runtime mistakes and
strengthen their code by proactively addressing errors found during compilation.
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. To
avoid this, two separate entries will be kept in a single hash bucket.
There are two ways to avoid hash collision.
1. Separate Chaining
According to this method, every bucket in the hashtable has a linked list of all the
key-value pairs that hash to the same index, or it can include another data
structure like a tree. When a collision occurs, the new key-value pair is just added
to the linked list connected to that bucket. This technique keeps hashtable
operations running at a substantially faster pace while allowing numerous entries
with the same hash value to coexist in the same bucket. However, because linked
lists need to be stored, there can be extra memory overhead, and if the linked
lists get too big, performance might suffer.
2. Open Addressing:
When a collision happens in open addressing, the hashtable looks for a different
place to store the clashing key-value pair. Open addressing can be achieved by a
variety of methods, including double hashing, quadratic probing, and linear
probing. For instance, linear probing entails scanning through the hashtable's
slots one after the other until an empty spot is discovered, at which point the
colliding element can be inserted.
Although open addressing eliminates the need to store extra data structures like
linked lists, it might cause performance deterioration and clustering when high
load factors are present.
Furthermore, the distribution of components and the effectiveness of hashtable
operations might be impacted by the probing technique selection.
23) What is the Dictionary class?
Java's Dictionary class makes key-value pair storage easier by providing methods
like put(), get(), remove(), and elements(). But because it's an abstract class,
putting it into practice involves subclassing. Because of its better features and
efficiency, Hashtable has mostly replaced Dictionary in current Java.
○ put(key, value): The method links the given value to the given key in the
dictionary.
○ get(key): Returns the value in the dictionary that corresponds to the given key.
○ remove(key): Empties the dictionary of the key and its corresponding value.
○ elements(): Provides a list of all the dictionary's values.
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 term "fail-fast" in Java refers to iterators or collection classes. During an
iteration, structural adjustments can involve the addition, deletion, or
modification of parts. Unlike other approaches that run the risk of unpredictable
behaviour or corrupted data, fail-fast behaviour guarantees that the iterator fails
promptly and consistently.
Fail-fast iterators guarantee the integrity of the collection by supplying instant
feedback in the event that concurrent alterations are discovered without requiring
additional memory overhead.
26) What are the differences between Array and ArrayList?
The main differences between the Array and ArrayList are given below.
Aspect Array ArrayList
Size flexibility Arrays are of fixed size. ArrayList is dynamic in
size.
Type It is static type. It is dynamic type.
Data types It can store primitive It can only store objects,
types and objects. not primitives.
Declaration syntax It uses square brackets It uses <> for declaration
(for example, int[] arr). (for example,
ArrayListlist).
Framework affiliation It is not a part of Java It is a part of Java
Collections Framework. Collections Framework.
Access methods Direct access using Access through methods
indices. like get() and set().
Multi-dimensionality It supports It is inherently
multi-dimensional arrays. one-dimensional.
27) What are the differences 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 length property, but we can use size() method to get
the number of objects in the list.
Finding the length of the array
Int [] array = new int[4];
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("ankit");
list.add("nippun");
System.out.println(list.size());
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 a Java ArrayList that is Read-only by calling the
Collections.unmodifiableCollection() method. When we define an ArrayList as
Read-only, we cannot modify the collection through the add(), remove(), or set()
methods.
ReadOnlyArrayList.java
import java.util.*;
public class ReadOnlyArrayList {
public static void main(String[] args) {
// Create a normal ArrayList
ArrayList<String> originalList = new ArrayList<>();
originalList.add("Apple");
originalList.add("Banana");
originalList.add("Orange");
// Make the ArrayList read-only
List<String> readOnlyList = Collections.unmodifiableList(originalList);
// Try to modify the read-only list (will throw UnsupportedOperationException)
try {
readOnlyList.add("Grape"); // Trying to add an element
} catch (UnsupportedOperationException e) {
System.out.println("Cannot add elements to the read-only list.");
}
// Try to modify the original list (will be reflected in the read-only list)
originalList.add("Grape");
// Display the read-only list
System.out.println("Read-only list: " + readOnlyList);
}
}
Output:
Cannot add elements to the read-only list. Read-only list: [Apple, Banana, Orange, Grape]
30) How to remove duplicates from ArrayList?
There are two ways to remove duplicates from the ArrayList.
○ Using HashSet: By using HashSet we can remove the duplicate element from the
ArrayList, but it will not then preserve the insertion order.
○ 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:
○ Copy all the elements of ArrayList to LinkedHashSet.
○ Empty the ArrayList using clear() method, which will remove all the elements
from the list.
○ Now copy all the elements of LinkedHashset to ArrayList.
31) How to reverse ArrayList?
To reverse an ArrayList, we can use reverse() method of Collections class.
Consider the following example.
ReverseArrayList.java
import java.util.*;
public class ReverseArrayList {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(10);
list.add(50);
list.add(30);
Iterator i = list.iterator();
System.out.println("printing the list....");
while(i.hasNext())
{
System.out.println(i.next());
}
Iterator i2 = list.iterator();
Collections.reverse(list);
System.out.println("printing list in reverse order....");
while(i2.hasNext())
{
System.out.println(i2.next());
}
}
}
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.
ReverseArrayList.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class ReverseArrayList {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(10);
list.add(50);
list.add(30);
list.add(60);
list.add(20);
list.add(90);
Iterator i = list.iterator();
System.out.println("printing the list....");
while(i.hasNext())
{
System.out.println(i.next());
}
Comparator cmp = Collections.reverseOrder();
Collections.sort(list,cmp);
System.out.println("printing list in descending order....");
Iterator i2 = list.iterator();
while(i2.hasNext())
{
System.out.println(i2.next());
}
}
}
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.
1. Using Collections.synchronizedList() Method
With this method, the Collections class's synchronisedList() methods are
wrapped around your ArrayList. It makes the list thread-safe by guaranteeing that
only one thread can access it at a time.
2. Using CopyOnWriteArrayList<T>
This is a customised version of Java's built-in synchronization-supporting List
interface. Every time an action is done that modifies the underlying array, a new
copy of it is made. This eliminates the requirement for explicit synchronisation
and permits safe concurrent access to the list.
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. While it's true that ArrayLists and
LinkedLists have different performance characteristics that make them more
suitable for certain operations, the decision on when to use one over the other
should consider various factors beyond just update and search operations.
ArrayList:
○ Use ArrayList when you need fast access to elements by index, as it provides
constant-time access to elements based on their position.
○ ArrayList is efficient for read-heavy scenarios where elements are frequently
accessed but less frequently modified.
○ It's also suitable when memory overhead is a concern, as ArrayLists have a
smaller memory footprint compared to LinkedLists due to their simple
array-based structure.
LinkedList:
○ Use LinkedList when you require frequent insertions or deletions at arbitrary
positions within the list, as it provides constant-time insertion and deletion
operations.
○ LinkedList performs better than ArrayList for frequent modifications, especially
when inserting or removing elements from the middle of the list, as it doesn't
require shifting of elements.
○ It's suitable for scenarios where you need to iterate over the entire list and
perform modifications, as LinkedList's iterator performs better in such cases
compared to ArrayList's iterator.