IA1 Tentitive
IA1 Tentitive
Elucidate List, Set and Map interfaces in Collection Framework in java with its types,
methods and properties
List: An ordered collection (like an array but dynamic in size). Examples: ArrayList, LinkedList.
Ordered collection
Allows duplicates
Indexed access
Methods: get(), set(), add(index, element)
Set: A collection that does not allow duplicate elements. Examples: HashSet, TreeSet.
No duplicates allowed
Unordered collection
Useful for uniqueness checks
Map: A collection of key-value pairs, where each key is unique. Examples: HashMap,TreeMap.
Key-value pairs
Unique keys
Methods: put(), get(), remove()
Key Characteristics:
b) LinkedList:
Key Characteristics:
Double linked list implementation
Fast insertions/deletions
Slow random access
Best for: Frequent insertions/deletions
c) HashSet:
Key Characteristics:
d) HashMap:
Key Characteristics:
Not ordered:
Thread-unsafe
e) TreeSet:
Key Characteristics:
Ordered
Slower than HashSet
Best for: Sorted unique elements
Q3. Explain the Syntax of HashMap interface with basic operation of adding 3 elements into it,
accessing elements, updating value, not updating if key already exist , removing element and
conditional remove
// 1. Basic Operations
// Adding elements
hashMap.put("Apple", 1);
hashMap.put("Banana", 2);
hashMap.put("Orange", 3);
System.out.println("Initial HashMap: " + hashMap);
// Updating value
hashMap.put("Apple", 5); // Updates existing value
System.out.println("After updating Apple's value: " + hashMap);
// putIfAbsent
hashMap.putIfAbsent("Apple", 10); // Won't update as key exists
hashMap.putIfAbsent("Grape", 4); // Will add new entry
System.out.println("After putIfAbsent operations: " + hashMap);
// 2. Accessing Elements
System.out.println("\nAccessing Elements:");
System.out.println("Value for Apple: " + hashMap.get("Apple"));
System.out.println("Value for missing key: " + hashMap.get("Mango"));
System.out.println("Value for missing key with default: " + hashMap.getOrDefault("Mango", 0));
// 3. Removing Elements
hashMap.remove("Banana");
System.out.println("After removing Banana: " + hashMap);
// Conditional remove
hashMap.remove("Apple", 5); // Removes only if value matches
System.out.println("After conditional remove: " + hashMap);
Q4. Explain the Syntax of HashSet interface with basic operation of adding 4 ( including one
dulplicate) elements , Checking size and empty status, Checking element existence, Removing
elements
// HashSet Demo
System.out.println("=== HashSet Demonstration ===");
Set<String> hashSet = new HashSet<>();
// 1. Adding elements
System.out.println("\nAdding elements to HashSet:");
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
hashSet.add("Apple"); // Duplicate - will not be added
System.out.println("HashSet after adding elements: " + hashSet);
// 4. Removing elements
hashSet.remove("Banana");
System.out.println("After removing 'Banana': " + hashSet);
Q5. Implement a multi-level sorting program for a collection of Student objects with fields name,
grade, age, and enrollmentId. The program should demonstrate the use of the Comparator
interface to:
1. Sort students by grade in descending order
2. If grades are equal, sort by name in ascending order
3. If names are also equal, sort by age in ascending order
package Collections.sortdemo;
import java.util.*;
class Student {
private String name;
private double grade;
private int age;
private String enrollmentId;
// Getters
public String getName() { return name; }
public double getGrade() { return grade; }
public int getAge() { return age; }
public String getEnrollmentId() { return enrollmentId; }
@Override
public String toString() {
return String.format("Student [name=%s, grade=%.1f, age=%d, id=%s]",
name, grade, age, enrollmentId);
}
}
// By name (ascending)
int nameComparison = s1.getName().compareTo(s2.getName());
if (nameComparison != 0) {
return nameComparison;
}
// By age (ascending)
int ageComparison = Integer.compare(s1.getAge(), s2.getAge());
if (ageComparison != 0) {
return ageComparison;
}
// By enrollmentId (ascending)
return s1.getEnrollmentId().compareTo(s2.getEnrollmentId());
}
});
o/p
Shuffled list:
Student [name=Eve, grade=85.5, age=20, id=E5006]
Student [name=Alice, grade=85.5, age=20, id=A1001]
Student [name=David, grade=92.0, age=20, id=D4005]
Student [name=Charlie, grade=78.5, age=21, id=C3003]
Student [name=Alice, grade=85.5, age=19, id=A1004]
Student [name=Alice, grade=85.5, age=20, id=A1007]
Student [name=Bob, grade=92.0, age=22, id=B2002]
List: An ordered collection (like an array but dynamic in size). Examples: ArrayList, LinkedList.
Ordered collection
Allows duplicates
Indexed access
Methods: get(), set(), add(index, element)
Set: A collection that does not allow duplicate elements. Examples: HashSet, TreeSet.
No duplicates allowed
Unordered collection
Useful for uniqueness checks
Queue: A collection designed to hold elements before processing. It typically follows the FIFO
(First-In-First-Out) principle. Examples: LinkedList, PriorityQueue.
Methods: offer(), poll(), peek()
Map: A collection of key-value pairs, where each key is unique. Examples: HashMap,TreeMap.
Key-value pairs
Unique keys
Methods: put(), get(), remove()
package Collections;
import java.util.*;
class IterationComparisionDemo1 {
public static void main(String[] args) {
// Creating a list of numbers for demonstration
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
System.out.println("Original list: " + numbers);
Q8. Write program to get all the following string elements into a LinkedList called Ls and extract
the sub elements from 1 to 3 and print them on console.["Orange","geen","pink","red","Blue"]
import java.util.*;
public class p4 {
Q9. Write program to get the numbers from 1 to 10 through bulk addition method into a
ArrayList called Al and remove all the odd numbers one by one and display the removed
numbers on the console and print all the remaining elements on the console finally
package Collections;
import java.util.*;
class OddRemovalDemo {
public static void main(String[] args) {
// Creating a list of numbers for demonstration
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
o/p
Q10. Differentiate Iterator and for-each loop with their advantages, key limitations of for-each
and Special features of Iterator along with their usuages
1 Iterator Advantages:
Supports element removal during iteration (iterator.remove())
Allows element modification (using ListIterator)
Provides bidirectional traversal (using ListIterator)
Offers more control over the iteration process
2 For-each Loop Advantages:
More concise and readable syntax
Less error-prone for simple iterations
Generally preferred for read-only operations
Cleaner syntax for nested iterations
3 Key Limitations:
For-each loop cannot modify the collection during iteration
For-each loop doesn't provide index information
For-each loop doesn't support backward iteration
4 Special Features:
ListIterator's bidirectional capabilities
Safe modification methods with Iterator
Performance comparison
Nested iteration patterns
5. Iterator is better when you need to:
Modify the collection while iterating
Need bidirectional traversal
Require more control over the iteration process
Q11. Write a program using the interface LinkedHashMap from Java collections to add the
following elements into the object called invensions and print the following o/p using foreach.
(“Electric Bulb” , “Edison”), (“Steam Engine”,”Jonh watts”),(“Aeroplane”, “Right brothers”),
(“Radio” , “Marconi”)
o/p : Electric Bulb was developed by Edison, Steam Engine was developed by Jonh watts, Areoplane
was developed by Right brothers, Radio was developed by Markcony
package Collections;
import java.util.*;
import java.util.Map.Entry;
}
o/p
Electric Bulb was developed by Edison
Steam Engine was developed by Jonh watts
Areoplane was developed by Right brothers
Radio was developed by Markcony
Q12. Write a program using the interface HashMap from Java collections to add the following
elements into the object called Map and print the o/p using foreach
(2,"Strawberry"), (4,"Cucumber"), (5,"Grapes"), (1,"Apple"), (3,"Pear"), (2,"Strawberry")
package Collections;
import java.util.HashMap;
import java.util.Map;
public class P7 {
Map.put(2,"Strawberry");
Map.put(4,"Cucumber");
Map.put(5,"Grapes");
Map.put(1,"Apple");
Map.put(3,"Pear");
Map.put(2,"Strawberry");
o/p
After Adding All elements , o/p is : {1=Apple, 2=Strawberry, 3=Pear, 4=Cucumber, 5=Grapes}
Q13. Define a class called Employee with fields name, salary, depart with constructor for getting
values as follows through parameters from main class.
("Alice", 20000, "IT"), ("Bob", 25000, "CS"), ("Charlie", 23000, "IT"), ("David", 30000,
"CS"),
("Larance", 40000, "IT")
Define comparators and print the set of objects as 1. byName (Ascending) 2. bySalaryDec 3.
bySalaryAsc 4.byDepartAndbySalaryDec, 5.byDepartAndbySalaryAsc.
package Comparator;
import java.util.*;
// Getters
public String getName() { return name; }
public int getSalary() { return salary; }
public String getDepart() { return depart; }
@Override
public String toString() {
return "Employee{name='" + name + "', salary=" + salary+ ", Depart=" + depart + "}";
}
}
o/p
Sorted by Name:
Student{name='Alice', salary=20000, Depart=IT}
Student{name='Bob', salary=25000, Depart=CS}
Student{name='Charlie', salary=23000, Depart=IT}
Student{name='David', salary=30000, Depart=CS}
Student{name='Larance', salary=40000, Depart=IT}
Sorted bySalary(descending):
Student{name='Larance', salary=40000, Depart=IT}
Student{name='David', salary=30000, Depart=CS}
Student{name='Bob', salary=25000, Depart=CS}
Student{name='Charlie', salary=23000, Depart=IT}
Student{name='Alice', salary=20000, Depart=IT}
Sorted bySalary(ascending):
Student{name='Alice', salary=20000, Depart=IT}
Student{name='Charlie', salary=23000, Depart=IT}
Student{name='Bob', salary=25000, Depart=CS}
Student{name='David', salary=30000, Depart=CS}
Student{name='Larance', salary=40000, Depart=IT}
Q14. Define ArrayList in Java Collections with syntax . Explain the following methods with Java
example programs
1) binarySearch() (from [1,2,3,4,5] , finds the elements
2) copy() ( source= [ "Apple","Banana","Cherry"], copy into another ArrayList called
destination )
3) equals() ( L1=[1,2,3], L2=[1,2,3], L3=[3,2,1] , compares L1 with L2 and L1 with L3)
4) fill() ( L1=["One", "Two", "Three", "Four"], fill with “Default” )
ArrayList is a resizable array implementation of the List interface in Java Collections Framework. It
provides dynamic arrays that can grow as needed.
import java.util.ArrayList;
import java.util.Collections;
}
}
import java.util.ArrayList;
import java.util.Collections;
Collections.copy(dest, source);
The equals() method in ArrayList compares the specified object with the list for equality.
import java.util.ArrayList;
import java.util.Arrays;
// Comparing two lists with the same elements in the same order
System.out.println("list1 equals list2: " + list1.equals(list2)); // Output: true
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
o/p
Q15. Define Queue interface in Java Collections with Syntax and Explain the important methods
in Queue Interface with examples.
Queue is an interface in the Java Collections Framework that represents a collection designed for
holding elements prior to processing, typically in FIFO (First-In-First-Out) order.
Syntax
Queue<E> queue = new LinkedList<>();
// Other implementations
import java.util.LinkedList;
import java.util.Queue;
try {
queue.remove(); // Will throw NoSuchElementException
} catch (Exception e) {
System.out.println("Exception with remove on empty queue: " +
e.getClass().getSimpleName());
}
o/p
Queue: [First, Second, Third]
Head (element): First
Head (peek): First
Removed: First
Queue after remove: [Second, Third]
Polled: Second
Queue after poll: [Third]
Exception with remove on empty queue: NoSuchElementException
Poll on empty queue returns: null
TreeMap
package Collections;
import java.util.Map;
import java.util.TreeMap;
package Collections;
import java.util.Map;
import java.util.TreeMap;
}
}
o/p
Products in alphabetical order:
Headphones: $159.99
Laptop: $999.99
Phone: $699.5
Smartwatch: $249.95
Tablet: $349.99
HashMap
package Collections;
import java.util.HashMap;
import java.util.Map;
// Update a value
studentScores.put("Charlie", 82);
System.out.println("Charlie's updated score: " + studentScores.get("Charlie"));
o/p
Bob's score: 89
Contains Edward? false
Contains score 92? true
Charlie's updated score: 82
Number of students: 3
After clearing, map is empty: true
Q17. Compare Comparable and Comparator interfaces in Java each with example program
Both Comparable and Comparator are interfaces in Java used to sort objects, but they serve different
purposes and are implemented differently.
Comparable
The Comparable interface is implemented by a class to define its "natural ordering." It has a single
method:
Key characteristics:
Example
package Comparable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
o/p
Student{name='Bob', rollNumber=101'}
Student{name='Charlie', rollNumber=102'}
Student{name='Alice', rollNumber=103'}
Comparator
The Comparator interface is external to the class being compared and defines custom ordering. It
has a primary method:
Key characteristics:
Example
package Comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator; // Missing import for Comparator
import java.util.List;
@Override
public String toString() {
return "Student{name='" + name + "', rollNumber=" + rollNumber + ", gpa=" + gpa + "}";
}
// Sort by name
Collections.sort(students, new NameComparator());
System.out.println("Sorted by name:"); // Missing print statement
for (Student s : students) {
System.out.println(s);
}
// Sort by GPA
Collections.sort(students, new GpaComparator());
System.out.println("\nSorted by GPA:");
for (Student s : students) {
System.out.println(s);
}
}
}
o/p
Sorted by name:
Student{name='Alice', rollNumber=103, gpa=3.8}
Student{name='Bob', rollNumber=101, gpa=3.9}
Student{name='Charlie', rollNumber=102, gpa=3.7}
Sorted by GPA:
Student{name='Bob', rollNumber=101, gpa=3.9}
Student{name='Alice', rollNumber=103, gpa=3.8}
Student{name='Charlie', rollNumber=102, gpa=3.7}
Q18. Elucidate the concept of Random Access Interface and Sequential Access Interface with a
suitable example program for making Performance comparison between random and sequential
access
RandomAccess interface:
In data structures, "random access" refers to the ability to access any element directly by its index
in constant time O(1), regardless of the element's position.
ArrayList provides random access because:
Purpose:
Key Characteristics:
When to Use:
Performance Implications:
Binary search
Random access iterations
Sorting algorithms
Best Practices:
package Collections;
import java.util.*;
class RandomAccessDemo {
// Utility method to measure access time using for loop (random access)
private static long measureRandomAccessTime(List<Integer> list) {
long startTime = System.nanoTime();
startTime = System.nanoTime();
Collections.binarySearch(linkedList, 50000);
System.out.println("LinkedList binary search time: " +
(System.nanoTime() - startTime) + " ns");
}
}
o/p
19. Elucidate Legacy classes and interfaces with a suitable example program.
Vector:
Hashtable:
Dictionary:
Stack:
Properties:
Extends Hashtable
Used for storing configuration settings
Key methods:
Enumeration Interface:
Important Notes:
These classes are considered legacy but still supported for backward compatibility
Modern alternatives are generally preferred:
Program
package Collections;
import java.util.*;
// 2. Hashtable demonstration
System.out.println("\n2. Hashtable Example:");
Hashtable<Integer, String> hashtable = new Hashtable<>();
hashtable.put(1, "One");
hashtable.put(2, "Two");
hashtable.put(3, "Three");
System.out.println("Dictionary elements:");
Enumeration<Integer> dictKeys = dictionary.keys();
while (dictKeys.hasMoreElements()) {
Integer key = dictKeys.nextElement();
System.out.println("Key: " + key + ", Value: " + dictionary.get(key));
}
// 4. Stack demonstration
System.out.println("\n4. Stack Example:");
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Stack elements:");
while (!stack.empty()) {
System.out.println("Popped: " + stack.pop());
}
// 5. Properties demonstration
System.out.println("\n5. Properties Example:");
Properties properties = new Properties();
properties.setProperty("database.url", "jdbc:mysql://localhost:3306/db");
properties.setProperty("database.user", "admin");
properties.setProperty("database.password", "password");
System.out.println("Properties elements:");
Enumeration<?> propertyNames = properties.propertyNames();
while (propertyNames.hasMoreElements()) {
String propertyName = (String) propertyNames.nextElement();
System.out.println(propertyName + " = " + properties.getProperty(propertyName));
}
// 6. BitSet demonstration
System.out.println("\n6. BitSet Example:");
BitSet bitSet = new BitSet(8);
bitSet.set(0); // Set first bit
bitSet.set(2); // Set third bit
bitSet.set(4); // Set fifth bit
System.out.println("BitSet elements:");
for (int i = 0; i < 8; i++) {
System.out.println("Bit " + i + " is set: " + bitSet.get(i));
}
}
}
o/p
1. Vector Example:
Vector size: 3
Vector capacity: 10
Vector capacity after trim: 3
2. Hashtable Example:
3. Dictionary Example:
Dictionary elements:
Key: 2, Value: Second
Key: 1, Value: First
4. Stack Example:
Stack elements:
Popped: 3
Popped: 2
Popped: 1
5. Properties Example:
Properties elements:
database.password = password
database.user = admin
database.url = jdbc:mysql://localhost:3306/db
6. BitSet Example:
BitSet elements:
Bit 0 is set: true
Bit 1 is set: false
Bit 2 is set: true
Bit 3 is set: false
Bit 4 is set: true
Bit 5 is set: false
Bit 6 is set: false
Bit 7 is set: false
Q20. All Lab1 and Lab2 Exercise Programs.( Already uploaded in the google class room)