Unit 04 Java
Unit 04 Java
Description:
Iterable: The root interface, implemented by all collection classes, enabling iteration
using for-each.
Collection: Base interface for all collections except Map.
List: Ordered collection that allows duplicates.
Set: Unordered collection with no duplicates.
Queue: Follows FIFO (First In, First Out).
Map: Stores key-value pairs, with unique keys.
4. What is the Iterator Interface? What is the purpose of the Iterator Interface in Java
Collections Framework?
The Iterator interface in Java is used to iterate over the elements of a collection. It provides
a universal way to traverse all types of collections (List, Set, etc.).
Key Methods of Iterator Interface:
hasNext() – Checks if there is another element.
next() – Returns the next element.
remove() – Removes the current element from the collection (optional operation).
Purpose of Iterator Interface:
Uniform Traversal: Allows iterating through any collection class without exposing its
internal structure.
Safe Removal: Allows elements to be removed safely during iteration.
Improves Code Reusability: Code using Iterator can work with any type of collection.
Contains
Basic collection operations Static methods like sort(), reverse()
Methods
Collections.sort(list),
Example List, Set implement Collection
Collections.emptyList()
7. What is the List Interface? What are the key characteristics of the List Interface?
The List interface in Java is a sub-interface of the Collection interface that represents an
ordered group of elements. It allows storing duplicate elements, and each element is
associated with a specific position (index) in the list. Lists are very useful when the order of
insertion matters or when the elements need to be accessed by their index. The List
interface is defined in the java.util package and is implemented by several commonly used
classes such as ArrayList, LinkedList, Vector, and Stack.
A key feature of the List interface is that it allows random access to elements using their
index (starting from 0). Lists can contain null elements and also duplicate values, which
makes them different from Set.
Java provides various operations through the List interface, such as adding, removing,
updating, and retrieving elements by index. Lists also support ListIterator, which allows both
forward and backward traversals, unlike the basic Iterator.
Key Characteristics of the List Interface:
Maintains Insertion Order: Elements are stored and retrieved in the same sequence
in which they are added.
Allows Duplicates: Lists can contain multiple instances of the same element.
Index-Based Access: Each element is assigned a numerical index; elements can be
accessed directly by this index using methods like get(int index).
Null Allowed: One or more null elements are allowed.
Modifiable: Elements can be inserted, deleted, or replaced.
ListIterator Support: Provides a special iterator that can move in both forward and
reverse directions.
Useful Methods: Includes many useful methods like add(int index, E element),
remove(int index), set(int index, E element), indexOf(Object o), etc.
Real-Life Use Cases:
To store a shopping cart where duplicate items can exist.
Maintaining a list of students, tasks, or chapters in a sequence.
Implementing a playlist, where items can be rearranged by position.
The List interface is ideal when there is a need to maintain ordered, indexed, and possibly
duplicate data in a dynamic structure.
8. What classes implement the List interface?
The List interface in Java is implemented by several concrete classes, each providing a
different internal mechanism and use-case-specific behavior. These classes belong to the
java.util package and are used based on the requirements like speed, memory, thread safety,
or element access pattern. The four major classes that implement the List interface are
ArrayList, LinkedList, Vector, and Stack.
1. ArrayList
ArrayList is the most commonly used List implementation. Internally, it uses a dynamic array
to store elements. It allows fast access by index, which makes it ideal for scenarios where
data is read frequently, but not modified often.
Maintains insertion order
Allows random access using index
Slower in insertions/removals (especially in the middle of the list)
2. LinkedList
LinkedList uses a doubly linked list internally. It is efficient for frequent insertions and
deletions, especially in the middle or beginning of the list. However, random access is slower
since it has to traverse from one node to another.
Efficient for add/remove operations
Allows null and duplicates
Performs poorly in random access
3. Vector
Vector is similar to ArrayList in terms of storage and behavior but is synchronized. This
means all its methods are thread-safe, making it suitable for multi-threaded environments,
but also relatively slower due to synchronization overhead.
Thread-safe (synchronized)
Slower than ArrayList
Maintains order and allows duplicates
4. Stack
Stack is a subclass of Vector and follows Last-In-First-Out (LIFO) order. It is used when the
latest element added needs to be removed first. It has methods like push(), pop(), and
peek() for stack operations.
LIFO structure
Built over Vector (hence synchronized)
Useful in problems like expression evaluation, recursion, undo operations
Each of these implementations serves a specific purpose. The choice among them depends
on factors like performance, order, synchronization, and the required type of data
operations.
10. Compare and contrast ArrayList, LinkedList, Vector, and Stack classes in Java.
Here's a tabular comparison of the four key List implementations in Java:
Internal
Dynamic Array Doubly Linked List Dynamic Array Inherits Vector
Structure
Fast (O(1)
Access Speed Slow (O(n) traversal) Fast (O(1)) Moderate
random access)
Order
Yes Yes Yes Yes
Maintained
14. Discuss the significance of the Set interface and its implementation (HashSet,
LinkedHashSet, TreeSet).
The Set interface is significant in Java because it provides a structure to store unique
elements. This is essential in many programming scenarios where duplication must be
avoided, such as storing keys, IDs, tags, or configurations.
Each implementation of the Set interface provides distinct advantages:
1. HashSet
Best performance for adding, removing, and searching elements.
Internally uses a hash table.
Ideal when order is not important.
Allows a single null element.
2. LinkedHashSet
Maintains insertion order.
Internally combines hash table with a doubly linked list.
Useful when order of entry needs to be preserved while avoiding duplicates.
3. TreeSet
Maintains sorted order (ascending by default).
Uses a Red-Black Tree structure.
Does not allow null.
Ideal for applications where elements must remain sorted (e.g., leaderboard,
alphabetical names).
Significance Summary:
Ensures data integrity by preventing duplicates.
Provides variety to suit different use cases (unordered, ordered, sorted).
Offers performance-tuned structures depending on the type of operations required.
15. How does the Queue interface differ from the Set interface in Java Collections
Framework?
Although both Queue and Set interfaces extend the Collection interface, they serve different
purposes and exhibit different behaviors.
Key Differences:
Element
Uses poll(), peek(), offer() Uses add(), contains(), remove()
Access
17. Describe SortedSet and SortedList interfaces. Also, give their key characteristics.
In Java, the SortedSet interface is a specialized form of Set that maintains its elements in a
sorted ascending order. It is a sub-interface of Set and is implemented primarily by the
TreeSet class. Elements in a SortedSet must be mutually comparable, either via natural
ordering (i.e., the elements implement Comparable) or via a custom comparator provided at
set creation. This interface ensures that all elements are unique and arranged in a defined
sequence, which is particularly useful in applications that require consistently ordered data.
Java does not provide a direct SortedList interface in the Collections Framework. However,
developers can achieve sorted lists by manually sorting List implementations like ArrayList or
LinkedList using Collections.sort() or Java 8 stream operations. Unlike SortedSet, these lists
can contain duplicate elements and are not automatically sorted—sorting must be explicitly
applied each time the list changes.
To summarize, SortedSet provides automatic sorting with uniqueness, whereas the concept
of a sorted list relies on applying sorting manually to a List. The choice depends on whether
automatic ordering and uniqueness are needed (SortedSet) or whether ordering is flexible
and duplicates are allowed (List).
20. Explain Map interface in Java. Write down the characteristics of Map interface.
The Map interface in Java is part of the java.util package and represents a collection of key-
value pairs, where each key is mapped to a corresponding value. Unlike the Collection
interface, Map is not a true child of Collection, as it does not represent a group of individual
elements but a mapping between two related values. Each key in a Map must be unique, but
values may be duplicated.
The Map interface provides various methods to add, remove, update, and query entries.
These include put(key, value) for adding pairs, get(key) for retrieving values, remove(key) for
deleting entries, and containsKey(key) or containsValue(value) to check presence. It also
provides views of its data through keySet(), values(), and entrySet() methods, which allow
iteration over keys, values, or entire entries.
The interface is implemented by several classes such as HashMap, LinkedHashMap,
TreeMap, and Hashtable, each offering distinct features. HashMap offers fast access without
order, LinkedHashMap maintains insertion order, TreeMap sorts keys, and Hashtable is
synchronized for thread safety.
In real-world use, the Map interface is invaluable for tasks that involve associative data, such
as mapping user IDs to usernames, product codes to prices, or configuration settings to their
values. Its flexible and powerful structure makes it one of the most widely used data types in
Java programming.
21. What is the role of the Map interface in Java Collection Framework?
The Map interface plays a crucial role in the Java Collection Framework by providing a
structure that allows developers to associate keys with corresponding values. Unlike other
collection types like List or Set, which store individual elements, a Map stores pairs of data
(key-value pairs). This makes it extremely useful for real-world data modeling, such as
storing student roll numbers with names, product IDs with their prices, or employee IDs with
records.
The key feature of the Map interface is that it ensures each key is unique, although multiple
keys can map to the same value. It supports fast access and retrieval of values using keys,
which significantly improves program efficiency. The interface also provides methods for
iterating over keys, values, or entries, allowing developers to perform complex operations
such as sorting by keys, filtering values, or updating specific mappings.
The Map interface is implemented by several classes—each tailored for different needs. For
example, HashMap provides fast and unordered key-value storage, LinkedHashMap
maintains insertion order, TreeMap keeps keys sorted, and Hashtable offers synchronized
access for multi-threading. This variety ensures that developers can choose the most
suitable map based on their specific performance and ordering requirements.
Overall, the Map interface is essential in Java’s Collection Framework for handling
associative data structures in an organized and efficient manner.
23. Explain the difference between HashMap, LinkedHashMap, TreeMap, and Hashtable
classes in tabular format.
Sorted based on
Maintains insertion
Ordering No specific order keys No specific order
order
(natural/custom)
Synchronized
Thread Safety Not synchronized Not synchronized Not synchronized
(thread-safe)
Best when
Best for general Use in legacy or
Use Case insertion order Best for sorted data
key-value storage thread-safe apps
matters
27. When would you use the Comparator interface instead of the Comparable interface?
The Comparator interface should be used when you need multiple ways to sort the same
class or when you cannot modify the source code of the class you want to sort. In contrast,
the Comparable interface is used when the class itself has a natural and consistent sorting
order that doesn't change.
For instance, consider a Product class. If you want to sort products by price, rating, and
name based on user preferences, using separate Comparator implementations for each
scenario is ideal. This allows you to keep the sorting logic modular, reusable, and external to
the data class.
Also, when sorting objects from external libraries or legacy systems, where you cannot
change the class to implement Comparable, the Comparator interface becomes the only
option to define sorting behavior.
Thus, Comparator is best for dynamic, multiple, or external sorting strategies.
28. Differentiate between Comparable and Comparator interfaces in Java (Tabular Format).
Sorting Logic Location Inside the class being sorted External to the class
Modification
Requires modifying the class No need to modify the original class
Required
29. What is the Properties class in Java Collections Framework? Explain its purpose and
usage.
The Properties class in Java is a special type of Map that is used to store configuration data
in the form of key-value pairs, where both the key and value are of type String. It is a
subclass of the Hashtable class and is part of the java.util package. The main purpose of the
Properties class is to read, write, and manage application settings or environment
configurations, such as database connection strings, file paths, or user-defined variables.
Unlike regular Maps, the Properties class provides specialized methods to load data from
and save data to external .properties files, which are simple text files used to store
configuration data. These files use the syntax key=value for each setting. The class offers two
important methods:
load(InputStream inStream) to read from a properties file.
store(OutputStream out, String comments) to write data to a file.
The Properties class is widely used in enterprise applications to separate configuration
settings from source code, which allows developers to modify settings without recompiling
the application. This makes the software more flexible, customizable, and maintainable.
For example, instead of hardcoding database URLs and passwords into Java programs,
developers often place them in a file like config.properties and use the Properties class to
load them during program execution. This improves security, portability, and ease of
deployment.
In summary, the Properties class is a specialized utility in the Java Collections Framework
that helps developers manage key-value configuration data efficiently. Its ability to interact
with external .properties files makes it a vital tool in Java-based configuration management
and environment setup.