Module 1 Java Revision
Module 1 Java Revision
1. What are the various changes that collection framework underwent recently?(5M)
Sol.
Sol.
3. What is a collection framework? Describe interfaces of collection framework with
example and syntax of any two methods in each interface.(10M)
The Java Collections Framework (JCF) is a robust and standardized architecture that
provides efficient ways to store, retrieve, and manipulate groups of objects in Java. It consists of
a well-designed hierarchy of interfaces, implementations, and utility classes that support
various data structures like lists, sets, queues, and maps, along with powerful algorithms for
sorting, searching, and iteration.
Example: collection.add("Java");
Example: collection.addAll(otherCollection);
Syntax: E first()
Syntax: E last()
🔹 Method 1: offer(E e)
Definition: Inserts an element into the queue; returns false if the queue is full.
Example: queue.offer("Task1");
🔹 Method 2: poll()
Definition: Retrieves and removes the head of the queue; returns null if empty.
Syntax: E poll()
Sol.
In Java, user-defined classes (also called custom classes) can be stored in collections such as ArrayList,
LinkedList, HashSet, etc., just like built-in data types.
Allows handling complex real-world data like Student, Employee, Product, etc.
6. Demonstrate with an example how accessing a collection via an Iterator can be done.(6M)
In Java, the Iterator interface is used to sequentially access elements of a collection without
exposing the internal structure of that collection. It is a universal iterator because it can be used
to iterate over any collection type like ArrayList, HashSet, LinkedList, etc.
The Iterator interface is part of the java.util package and is available to all classes that
🔹
implement the Collection interface.
Common Methods of Iterator:
1. iterator()
This method is called on a collection (like ArrayList, HashSet, etc.) to obtain an iterator
object.
Example: Iterator<String> itr = list.iterator();
2. hasNext()
Returns true if there are more elements to iterate through. It checks if the next element
exists. It is Useful for creating loops to process all elements.
Example: while (itr.hasNext())
3. next()
Returns the next element in the collection. Should only be called after hasNext() returns
true.
Example: String item = itr.next();
7. What are comparators? Write a comparator program to sort accounts by last name.
(10M)
Sol.
Comparator Interface in Java
Declaration:
interface Comparator<T>
● Returns:
● Returns:
○ true → if both are Comparator objects and use the same ordering.
○ false → otherwise.
Usage:
import java.util.*;
// Constructor
Account(String firstName, String lastName, String accountNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.accountNumber = accountNumber;
}
// Before sorting
System.out.println("Before sorting:");
for (Account acc : accounts) {
System.out.println(acc);
}
// After sorting
System.out.println("\nAfter sorting by last name:");
for (Account acc : accounts) {
System.out.println(acc);
}
}
}
8. Explain the following collection classes by constructing a java program.(10M)
ArrayList in Java
Constructors of ArrayList
1. ArrayList()
Creates an empty ArrayList.
3. ArrayList(int capacity)
Creates an ArrayList with a specified initial capacity.
(Capacity grows automatically as new elements are added.)
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " + al.size());
// Add elements
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
// Remove elements
al.remove("F");
al.remove(2);
Output -
HashSet in Java
class HashSet<E>
HashSet(int capacity, float fillRatio) Creates a HashSet with the specified capacity and
load factor.
Example Program
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
HashSet<String> hs = new HashSet<String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
Output -
[D, A, F, C, B, E]
TreeSet in Java
● Ideal for storing large, sorted datasets with fast access and retrieval.
Key Features of TreeSet
class TreeSet<E>
Constructors of TreeSet
Constructor Description
Example Program
import java.util.*;
class TreeSetDemo {
public static void main(String args[]) {
TreeSet<String> ts = new TreeSet<String>();
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
}
}
Output
[A, B, C, D, E, F]
Constructor Description
HashSet(int capacity, float Creates an empty HashSet with the given initial
fillRatio) capacity and load factor.
1. HashSet() – Default Constructor
import java.util.*;
import java.util.*;
public class CollectionConstructorExample {
public static void main(String[] args) {
List<String> list = Arrays.asList("Red", "Green", "Blue", "Red");
HashSet<String> set = new HashSet<>(list);
Explanation: Removes duplicate "Red" and creates a set with unique elements from the list.
3. HashSet(int capacity)
import java.util.*;
Explanation: Initializes the set with space for 50 elements. Capacity expands when needed.
import java.util.*;
public class CapacityLoadConstructorExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>(20, 0.5f); // Initial capacity 20, load factor 0.5
set.add("One");
set.add("Two");
set.add("Three");
System.out.println("HashSet with custom capacity and load factor: " + set);
}
}
Explanation: Uses custom load factor (threshold for rehashing) for optimized
memory/performance.
10. Create a class STUDENT with two private numbers: USN, Name using LinkedList
class in java. Wap to add at least 3 objects of above STUDENT class and display the data.
(10M)
Sol.
11. Explain the methods of NavigableSet class with a sample program.(10M)
Sol.
12. What are the needs of ArrayList?(2M)
Sol.
1. Dynamic Sizing:
Unlike arrays, ArrayList can grow or shrink dynamically at runtime based on the
number of elements.
// Removing an element
fruits.remove("Mango");
Output -
Sol.
(i) Collections.binarySearch()
Syntax
int index = Collections.binarySearch(list, key);
● Returns:
○ Index of the element if found.
○ If not found, returns (-(insertion point) - 1).
Example:
(ii) Collections.copy()
Syntax:
Collections.copy(destList, sourceList);
Example:
(iii) equals()
Syntax:
boolean result = list1.equals(list2);
● Returns: true if both lists contain the same elements in the same order, otherwise false.
Example:
(iv) Collections.fill()
Syntax:
Collections.fill(list, value);
Example:
Sol.
import java.util.*;
class LinkedListDemo {
public static void main(String[] args) {
// Create a LinkedList of Strings
LinkedList<String> list = new LinkedList<>();
Output -
Sol.
import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a HashMap
HashMap<String, Double> hm = new HashMap<String, Double>();
System.out.println();
Output -
class TreeMapDemo {
public static void main(String args[]) {
// Create a TreeMap
TreeMap<String, Double> tm = new TreeMap<String, Double>();
System.out.println();
Output -
Sol.
The Java Collections Framework provides several interfaces to support maps, each serving a
distinct purpose.
1. Map Interface
Declaration:
○ K: Type of keys
○ V: Type of values
● Core Operations:
● Collection Views:
● Exceptions:
❗ Maps do not extend the Collection interface, but support integration via
collection-views.
2. SortedMap Interface
Declaration:
● Key Methods:
● Exceptions:
Declaration:
● Exceptions:
○ Same as in SortedMap.
4. Map.Entry Interface
Declaration:
● Methods:
Sol.
1. Vector
Vector is a legacy class that implements a dynamic array which can grow as needed. It is
synchronized and implements the List interface. It supports methods such as add(), remove(),
get(), and set().
🔹 Example:
names.add("Java");
names.add("Python");
System.out.println(names);
🔹 Example:
Stack<Integer> s = new Stack<>();
s.push(10);
s.push(20);
System.out.println(s.pop()); // 20
3. Dictionary
Dictionary is an abstract class that stores key/value pairs. Each key maps to a single value. It
is the original class for mapping before Map was introduced.
🔹 Example:
dict.put(1, "Java");
dict.put(2, "C++");
System.out.println(dict.get(1)); // Java
4. Hashtable
Hashtable is a concrete implementation of the Dictionary class that stores key/value pairs in a
hash table. It does not allow null keys or values and is synchronized.
🔹 Example:
ht.put(101, "Alice");
ht.put(102, "Bob");
System.out.println(ht.get(101)); // Alice
1. Vector Example
import java.util.Vector;
2. Stack Example
import java.util.Stack;
3. Dictionary Example
import java.util.Dictionary;
import java.util.Hashtable;
public class DictionaryExample {
public static void main(String[] args) {
Dictionary<Integer, String> dict = new Hashtable<Integer, String>();
dict.put(1, "Red");
dict.put(2, "Green");
dict.put(3, "Blue");
4. Hashtable Example
import java.util.Hashtable;
import java.util.Map;
public class HashtableExample {
public static void main(String[] args) {
Hashtable<String, Double> balance = new Hashtable<String, Double>();
balance.put("Alice", 1200.50);
balance.put("Bob", 850.75);
balance.put("Charlie", 1560.00);
System.out.println("Hashtable Balances:");
for (Map.Entry<String, Double> entry : balance.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Updating a value
double newBalance = balance.get("Alice") + 500;
balance.put("Alice", newBalance);
System.out.println("Updated balance for Alice: " + balance.get("Alice"));
}
}