0% found this document useful (0 votes)
40 views34 pages

IA1 Tentitive

The document provides an overview of various Java Collection Framework interfaces, including List, Set, and Map, detailing their characteristics, methods, and examples. It also includes specific implementations like ArrayList, LinkedList, HashSet, HashMap, and TreeSet, along with syntax and basic operations for manipulating these collections. Additionally, it demonstrates sorting of custom objects using the Comparator interface and discusses concurrent modification exceptions with solutions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views34 pages

IA1 Tentitive

The document provides an overview of various Java Collection Framework interfaces, including List, Set, and Map, detailing their characteristics, methods, and examples. It also includes specific implementations like ArrayList, LinkedList, HashSet, HashMap, and TreeSet, along with syntax and basic operations for manipulating these collections. Additionally, it demonstrates sorting of custom objects using the Comparator interface and discusses concurrent modification exceptions with solutions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Q1.

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()

Q2. Explain Key Characteristics of ArrayList, LinkedList, Hashset, Hashmap, Treeset


Collection interfaces in java with its syntax and methods for adding elements into them.
a) ArrayList:
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.get(0); // Returns "Apple"

Key Characteristics:

Dynamic array implementation


Fast random access
Slow insertions/deletions in middle
Best for: Random access and iteration

b) LinkedList:

LinkedList<Integer> numbers = new LinkedList<>();


numbers.addFirst(1);
numbers.addLast(3);

Key Characteristics:
Double linked list implementation
Fast insertions/deletions
Slow random access
Best for: Frequent insertions/deletions

c) HashSet:

HashSet<String> set = new HashSet<>();


set.add("One");
set.add("One"); // Duplicate not added

Key Characteristics:

Hash table implementation


Very fast access/search
Unordered
Best for: Uniqueness checking

d) HashMap:

HashMap<String, Integer> map = new HashMap<>();


// key-value pair
map.put("One", 1);
map.put("Two", 2);
map.get("One"); // Returns 1

Key Characteristics:

Not ordered:
Thread-unsafe

e) TreeSet:

Set<String> ts = new TreeSet<>();


// Elements are added using add() method
ts.add("I");
ts.add("Love");
ts.add("India");
System.out.println(ts); // returns [I, Love, India]

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

System.out.println("=== HashMap Demonstration ===");


Map<String, Integer> hashMap = new HashMap<>();

// 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);

// 2. Checking size and empty status


System.out.println("Size of HashSet: " + hashSet.size());
System.out.println("Is HashSet empty? " + hashSet.isEmpty());

// 3. Checking element existence


System.out.println("Contains 'Apple'? " + hashSet.contains("Apple"));
System.out.println("Contains 'Grape'? " + hashSet.contains("Grape"));

// 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;

public Student(String name, double grade, int age, String enrollmentId) {


this.name = name;
this.grade = grade;
this.age = age;
this.enrollmentId = 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);
}
}

public class MultiLevelSortDemo {


public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 85.5, 20, "A1001"));
students.add(new Student("Bob", 92.0, 22, "B2002"));
students.add(new Student("Charlie", 78.5, 21, "C3003"));
students.add(new Student("Alice", 85.5, 19, "A1004"));
students.add(new Student("David", 92.0, 20, "D4005"));
students.add(new Student("Eve", 85.5, 20, "E5006"));
students.add(new Student("Alice", 85.5, 20, "A1007"));

// Traditional approach with anonymous Comparator class


System.out.println("Original list of students:");

System.out.println("\nSorted using traditional Comparator approach:");


Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// By grade (descending)
int gradeComparison = Double.compare(s2.getGrade(), s1.getGrade());
if (gradeComparison != 0) {
return gradeComparison;
}

// 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());
}
});

for (Student student : students) {


System.out.println(student);
}

// Shuffle the list to demonstrate the next sort


Collections.shuffle(students);
System.out.println("\nShuffled list:");

for (Student student : students) {


System.out.println(student);
}

// Java 8+ approach with Comparator method chaining


System.out.println("\nSorted using Java 8 Comparator chaining:");
students.sort(
Comparator.comparing(Student::getGrade, Comparator.reverseOrder())
.thenComparing(Student::getName)
.thenComparing(Student::getAge)
.thenComparing(Student::getEnrollmentId)
);

for (Student student : students) {


System.out.println(student);
}

// Demonstrate partial sorting


System.out.println("\nDemonstrating partial sorting (by grade only, descending):");
students.sort(Comparator.comparing(Student::getGrade, Comparator.reverseOrder()));

for (Student student : students) {


System.out.println(student);
}

System.out.println("\nDemonstrating partial sorting (by name then age):");


students.sort(
Comparator.comparing(Student::getName)
.thenComparing(Student::getAge)
);
for (Student student : students) {
System.out.println(student);
}
}
}

o/p

Original list of students:


Student [name=Alice, grade=85.5, age=20, id=A1001]
Student [name=Bob, grade=92.0, age=22, id=B2002]
Student [name=Charlie, grade=78.5, age=21, id=C3003]
Student [name=Alice, grade=85.5, age=19, id=A1004]
Student [name=David, grade=92.0, age=20, id=D4005]
Student [name=Eve, grade=85.5, age=20, id=E5006]
Student [name=Alice, grade=85.5, age=20, id=A1007]

Sorted using traditional Comparator approach:


Student [name=Bob, grade=92.0, age=22, id=B2002]
Student [name=David, grade=92.0, age=20, id=D4005]
Student [name=Alice, grade=85.5, age=19, id=A1004]
Student [name=Alice, grade=85.5, age=20, id=A1001]
Student [name=Alice, grade=85.5, age=20, id=A1007]
Student [name=Eve, grade=85.5, age=20, id=E5006]
Student [name=Charlie, grade=78.5, age=21, id=C3003]

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]

Sorted using Java 8 Comparator chaining:


Student [name=Bob, grade=92.0, age=22, id=B2002]
Student [name=David, grade=92.0, age=20, id=D4005]
Student [name=Alice, grade=85.5, age=19, id=A1004]
Student [name=Alice, grade=85.5, age=20, id=A1001]
Student [name=Alice, grade=85.5, age=20, id=A1007]
Student [name=Eve, grade=85.5, age=20, id=E5006]
Student [name=Charlie, grade=78.5, age=21, id=C3003]

Demonstrating partial sorting (by grade only, descending):


Student [name=Bob, grade=92.0, age=22, id=B2002]
Student [name=David, grade=92.0, age=20, id=D4005]
Student [name=Alice, grade=85.5, age=19, id=A1004]
Student [name=Alice, grade=85.5, age=20, id=A1001]
Student [name=Alice, grade=85.5, age=20, id=A1007]
Student [name=Eve, grade=85.5, age=20, id=E5006]
Student [name=Charlie, grade=78.5, age=21, id=C3003]
Demonstrating partial sorting (by name then age):
Student [name=Alice, grade=85.5, age=19, id=A1004]
Student [name=Alice, grade=85.5, age=20, id=A1001]
Student [name=Alice, grade=85.5, age=20, id=A1007]
Student [name=Bob, grade=92.0, age=22, id=B2002]
Student [name=Charlie, grade=78.5, age=21, id=C3003]
Student [name=David, grade=92.0, age=20, id=D4005]
Student [name=Eve, grade=85.5, age=20, id=E5006]

Q6. Explain List,set,Queue and Map

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()

Q7. A program that demonstrates concurrent modification exception in Collection of ArrayList


having elements from 1 to 10 while trying to delete all odd numbers during iteration of foreach
loop. Explain how it can be solved through coding.

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);

// 1. For-each loop attempt to remove (will throw exception)


System.out.println("\n=== For-each loop with attempted removal ===");
try {
System.out.println("Attempting to remove elements using for-each loop:");
for (int num : numbers) {
if (num % 2 != 0) {
numbers.remove(Integer.valueOf(num)); // Will throw ConcurrentModificationException
}
}
} catch (ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException caught: Cannot modify list during for-
each loop");
}
// Reset list
numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

// 1. Iterator with removal


System.out.println("\n=== Iterator with element removal ===");
Iterator<Integer> iterator = numbers.iterator();
System.out.println("Removing even numbers using Iterator:");
while (iterator.hasNext()) {
int num = iterator.next();
if (num % 2 = 0) {
iterator.remove(); // Safe removal during iteration
System.out.println("Removed: " + num);
}
}
System.out.println("List after removing even numbers: " + 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 {

public static void main(String[] args) {


// TODO Auto-generated method stub
List<String> ls = new ArrayList<>();
ls.add("Orange");
ls.add("geen");
ls.add("pink");
ls.add("red");
ls.add("Blue");
System.out.println(ls);
System.out.println("using sublist:");
System.out.println(ls.subList(1,4));
}

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));

System.out.println("Original list: " + numbers);

// 1. Iterator with removal


System.out.println("\n=== Iterator with element removal ===");
Iterator<Integer> iterator = numbers.iterator();
System.out.println("Removing odd numbers using Iterator:");
while (iterator.hasNext()) {
int num = iterator.next();
if (num % 2 != 0) {
iterator.remove(); // Safe removal during iteration
System.out.println("Removed: " + num);
}
}
System.out.println("List after removing odd numbers: " + numbers);
}
}

o/p

Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

=== Iterator with element removal ===


Removing odd numbers using Iterator:
Removed: 1
Removed: 3
Removed: 5
Removed: 7
Removed: 9
List after removing odd numbers: [2, 4, 6, 8, 10]

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

6. For-each loop is better when you:


 Just need to read elements
 Want cleaner, more readable code
 Don't need to modify the collection
 Are working with nested collections

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;

public class P11 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Map<String,String> Invensions = new LinkedHashMap<>();
Invensions.put("Electric Bulb", "Edison");
Invensions.put("Steam Engine", "Jonh watts");
Invensions.put("Areoplane", "Right brothers");
Invensions.put("Radio", "Markcony");
for (Entry< String,String> entry :Invensions.entrySet()) {
System.out.println(entry.getKey() + " was developed by " + entry.getValue());
}
}

}
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 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Map< Integer,String> Map = new HashMap<>();
// 1. Basic Operations
// Adding elements

Map.put(2,"Strawberry");
Map.put(4,"Cucumber");
Map.put(5,"Grapes");
Map.put(1,"Apple");
Map.put(3,"Pear");
Map.put(2,"Strawberry");

System.out.println("After Adding All elements o/p is : "+Map);


}

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.*;

//Employee class to demonstrate sorting using comparators


class Employee {
private String name;
private int salary;
private String depart;

public Employee(String name, int salary, String depart) {


this.name = name;
this.salary = salary;
this.depart = depart;
}

// 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 + "}";
}
}

//Main class demonstrating different comparators


public class EmployeeSorting {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();

employees.add(new Employee("Alice", 20000, "IT"));


employees.add(new Employee("Bob", 25000, "CS"));
employees.add(new Employee("Charlie", 23000, "IT"));
employees.add(new Employee("David", 30000, "CS"));
employees.add(new Employee("Larance", 40000, "IT"));

// Comparator using anonymous class


Comparator<Employee> bySalaryAsc = new Comparator<Employee>() {
@Override
public int compare(Employee s1, Employee s2) {
return Integer.compare(s1.getSalary(), s2.getSalary());
}
};

// Comparator using anonymous class


Comparator<Employee> bySalaryDec = new Comparator<Employee>() {
@Override
public int compare(Employee s1, Employee s2) {
return Integer.compare(s2.getSalary(), s1.getSalary());
}
};

// Comparator using Comparator.comparing()


Comparator<Employee> byName = Comparator.comparing(Employee::getName);

// Comparator using Comparator.comparing()


Comparator<Employee> byDepart = Comparator.comparing(Employee::getDepart);

// Sort by Name and print


System.out.println("Sorted by Name:");
employees.sort(byName);
employees.forEach(System.out::println);

// Sort by Salary Descending and print


System.out.println("\nSorted bySalary(descending):");
employees.sort(bySalaryDec);
employees.forEach(System.out::println);

// Sort by Salary Ascending and print


System.out.println("\nSorted bySalary(ascending):");
employees.sort(bySalaryAsc);
employees.forEach(System.out::println);

// Chaining comparators (sort by depart, then salary descending)


Comparator<Employee> byDepartAndbySalaryDec = byDepart.thenComparing(bySalaryDec);
System.out.println("\nSorted by Depart, then Salary descending:");
employees.sort(byDepartAndbySalaryDec);
employees.forEach(System.out::println);

// Chaining comparators (sort by depart, then salary ascending)


Comparator<Employee> byDepartAndbySalaryAsc = byDepart.thenComparing(bySalaryAsc);
System.out.println("\nSorted by Depart, then Salary ascending:");
employees.sort(byDepartAndbySalaryAsc);
employees.forEach(System.out::println);
}
}

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}

Sorted by Depart, then Salary descending:


Student{name='David', salary=30000, Depart=CS}
Student{name='Bob', salary=25000, Depart=CS}
Student{name='Larance', salary=40000, Depart=IT}
Student{name='Charlie', salary=23000, Depart=IT}
Student{name='Alice', salary=20000, Depart=IT}

Sorted by Depart, then Salary ascending:


Student{name='Bob', salary=25000, Depart=CS}
Student{name='David', salary=30000, Depart=CS}
Student{name='Alice', salary=20000, Depart=IT}
Student{name='Charlie', salary=23000, Depart=IT}
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.

// Creating an ArrayList ArrayList<E> arrayList = new ArrayList<E>(); // E is the type parameter

import java.util.ArrayList;
import java.util.Collections;

public class BinarySearchExample {


public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);

// List must be sorted for binary search to work correctly


int index = Collections.binarySearch(list, 30);
System.out.println("Element found at index: " + index); // Output: 2

}
}

import java.util.ArrayList;
import java.util.Collections;

public class CopyExample {


public static void main(String[] args) {
ArrayList<String> source = new ArrayList<>();
source.add("Apple");
source.add("Banana");
source.add("Cherry");

// Destination list must be at least as large as the source list


ArrayList<String> dest = new ArrayList<>(Collections.nCopies(source.size(), ""));
// Alternatively: create and initialize
// ArrayList<String> dest = new ArrayList<>(Arrays.asList("", "", ""));

Collections.copy(dest, source);

System.out.println("Source: " + source); // Output: [Apple, Banana, Cherry]


System.out.println("Destination: " + dest); // Output: [Apple, Banana, Cherry]
}
}

The equals() method in ArrayList compares the specified object with the list for equality.

import java.util.ArrayList;
import java.util.Arrays;

public class EqualsExample {


public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3));
ArrayList<Integer> list2 = new ArrayList<>(Arrays.asList(1, 2, 3));
ArrayList<Integer> list3 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

// Comparing two lists with the same elements in the same order
System.out.println("list1 equals list2: " + list1.equals(list2)); // Output: true

// Comparing two lists with different elements


System.out.println("list1 equals list3: " + list1.equals(list3)); // Output: false

// Order matters in equals comparison


ArrayList<Integer> list4 = new ArrayList<>(Arrays.asList(3, 2, 1));
System.out.println("list1 equals list4: " + list1.equals(list4)); // Output: false
}
}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class FillExample {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(Arrays.asList("One", "Two", "Three", "Four"));

System.out.println("Before fill: " + list); // Output: [One, Two, Three, Four]

// Replace all elements with "Default"


Collections.fill(list, "Default");
System.out.println("After fill: " + list); // Output: [Default, Default, Default, Default]
}
}

o/p

Before fill: [One, Two, Three, Four]


After fill: [Default, Default, Default, Default]

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

Queue<E> priorityQueue = new PriorityQueue<>();

Queue<E> arrayDeque = new ArrayDeque<>();

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {


public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();

// Adding elements (Insertion)


queue.add("First"); // Adds to the tail of the queue
queue.offer("Second");
queue.offer("Third"); // Similar to add but returns false instead of exception

System.out.println("Queue: " + queue); // Output: [First, Second, Third]

// Examining the element at the head without removing


System.out.println("Head (element): " + queue.element()); // Output: First
System.out.println("Head (peek): " + queue.peek()); // Output: First

// Removing elements (Retrieval)


System.out.println("Removed: " + queue.remove()); // Output: First
System.out.println("Queue after remove: " + queue); // Output: [Second, Third]

System.out.println("Polled: " + queue.poll()); // Output: Second


System.out.println("Queue after poll: " + queue); // Output: [Third]

// Difference between remove and poll when queue is empty


queue.poll(); // Queue becomes empty

try {
queue.remove(); // Will throw NoSuchElementException
} catch (Exception e) {
System.out.println("Exception with remove on empty queue: " +
e.getClass().getSimpleName());
}

System.out.println("Poll on empty queue returns: " + queue.poll()); // Output: null


}
}

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

Q16. Explain TreeMap and HashMap with example programs

TreeMap

package Collections;

import java.util.Map;
import java.util.TreeMap;
package Collections;

import java.util.Map;
import java.util.TreeMap;

public class TreeMapExample {


public static void main(String[] args) {
// Create a TreeMap (sorted by natural order of keys)
TreeMap<String, Double> productPrices = new TreeMap<>();
// Add items
productPrices.put("Laptop", 999.99);
productPrices.put("Phone", 699.50);
productPrices.put("Tablet", 349.99);
productPrices.put("Headphones", 159.99);
productPrices.put("Smartwatch", 249.95);

// Display in sorted order


System.out.println("Products in alphabetical order:");
for (Map.Entry<String, Double> entry : productPrices.entrySet()) {
System.out.println(entry.getKey() + ": $" + entry.getValue());
}

// TreeMap navigation methods


System.out.println("\nFirst product: " + productPrices.firstKey());
System.out.println("Last product: " + productPrices.lastKey());

}
}

o/p
Products in alphabetical order:
Headphones: $159.99
Laptop: $999.99
Phone: $699.5
Smartwatch: $249.95
Tablet: $349.99

First product: Headphones


Last product: Tablet

HashMap

package Collections;

import java.util.HashMap;
import java.util.Map;

public class HashMapExample {


public static void main(String[] args) {
// Create a HashMap
HashMap<String, Integer> studentScores = new HashMap<>();

// Add key-value pairs


studentScores.put("Alice", 95);
studentScores.put("Bob", 89);
studentScores.put("Charlie", 78);
studentScores.put("Diana", 92);
// Access a specific value
System.out.println("Bob's score: " + studentScores.get("Bob"));

// Check if key exists


System.out.println("Contains Edward? " + studentScores.containsKey("Edward"));

// Check if value exists


System.out.println("Contains score 92? " + studentScores.containsValue(92));

// Update a value
studentScores.put("Charlie", 82);
System.out.println("Charlie's updated score: " + studentScores.get("Charlie"));

// Remove a key-value pair


studentScores.remove("Diana");

// Iterate through the map


System.out.println("\nAll student scores:");
for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// Size of the map


System.out.println("\nNumber of students: " + studentScores.size());

// Clear the map


studentScores.clear();
System.out.println("After clearing, map is empty: " + studentScores.isEmpty());
}
}

o/p

Bob's score: 89
Contains Edward? false
Contains score 92? true
Charlie's updated score: 82

All student scores:


Bob: 89
Alice: 95
Charlie: 82

Number of students: 3
After clearing, map is empty: true
Q17. Compare Comparable and Comparator interfaces in Java each with example program

Comparable vs Comparator in Java

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:

public int compareTo(T o);

Key characteristics:

It's in the java.lang package


Objects implement this to compare themselves with another object
Used with Collections.sort() and Arrays.sort() without additional parameters

Example

package Comparable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Student implements Comparable<Student> {


private String name;
private int rollNumber;

public Student(String name, int rollNumber) {


this.name = name;
this.rollNumber = rollNumber;
}

// Natural ordering based on roll number


@Override
public int compareTo(Student other) {
return this.rollNumber - other.rollNumber;
}

// Add toString method to properly display the object


@Override
public String toString() {
return "Student{name='" + name + "', rollNumber=" + rollNumber + "'}";
}
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 103));
students.add(new Student("Bob", 101));
students.add(new Student("Charlie", 102));

// Sort using natural ordering (by roll number)


Collections.sort(students);

for (Student s : students) {


System.out.println(s);
}
}
}

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:

public int compare(T o1, T o2);

Key characteristics:

It's in the java.util package


Allows defining multiple different comparison strategies for the same class
Used with sort methods that accept a Comparator parameter

Example

package Comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator; // Missing import for Comparator
import java.util.List;

public class Student {


private String name;
private int rollNumber;
private double gpa;
public Student(String name, int rollNumber, double gpa) {
this.name = name;
this.rollNumber = rollNumber;
this.gpa = gpa;
}

// Missing getters needed by the comparators


public String getName() {
return name;
}

public int getRollNumber() {


return rollNumber;
}

public double getGpa() {


return gpa;
}

@Override
public String toString() {
return "Student{name='" + name + "', rollNumber=" + rollNumber + ", gpa=" + gpa + "}";
}

public static void main(String[] args) {


List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 103, 3.8));
students.add(new Student("Bob", 101, 3.9));
students.add(new Student("Charlie", 102, 3.7));

// 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);
}
}
}

// Comparator for sorting by name


class NameComparator implements Comparator<Student> {
@Override // Missing @Override annotation
public int compare(Student s1, Student s2) {
return s1.getName().compareTo(s2.getName());
}
}

// Comparator for sorting by GPA (descending)


class GpaComparator implements Comparator<Student> {
@Override // Missing @Override annotation
public int compare(Student s1, Student s2) {
// Sort in descending order
return Double.compare(s2.getGpa(), s1.getGpa());
}
}

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:

It stores elements in contiguous memory locations


You can directly access any element using its index: list.get(i) is an O(1) operation
The underlying array structure allows immediate calculation of any element's memory address

LinkedList does not provide random access because:

Elements are stored as separate nodes connected by references/pointers


To access the nth element, you must traverse the list from the beginning (or end) node by node
Accessing an element at position i requires O(i) or O(n-i) time complexity
There's no way to directly jump to a specific position without traversing through previous nodes
This difference in access patterns is why ArrayList is better for scenarios requiring frequent random
access to elements, while LinkedList is more efficient for frequent insertions/deletions in the
middle of the list.

Purpose:

RandomAccess is a marker interface (has no methods)


Indicates that a list supports fast random access operations
Used to optimize algorithms based on access patterns

Key Characteristics:

Constant-time positional access (O(1))


Implemented by ArrayList but not LinkedList
Used by Collections utility methods to choose optimal algorithms

When to Use:

For lists that will be frequently accessed by index


When binary search operations are common
In algorithms that require frequent random access

Performance Implications:

ArrayList: Fast random access, implements RandomAccess


LinkedList: Slow random access, doesn't implement RandomAccess

Affects performance of operations like:

Binary search
Random access iterations
Sorting algorithms

Best Practices:

Check for RandomAccess before choosing access strategy


Use iterator for non-RandomAccess lists
Use indexed for-loop for RandomAccess lists
Consider RandomAccess for custom List implementations

The example demonstrates:

• Performance comparison between random and sequential access


• How to check if a list implements RandomAccess
• Optimal access strategy selection
• Impact on binary search performance
• Practical usage in real-world scenarios

Key Observations from the Program:

ArrayList shows better performance with random access


LinkedList performs better with iterator access
Binary search is significantly faster on ArrayList

The interface helps in selecting the optimal access strategy

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();

// Perform random access operations


for (int i = 0; i < list.size(); i++) {
int element = list.get(i);
}

return System.nanoTime() - startTime;


}

// Utility method to measure access time using iterator


private static long measureIteratorAccessTime(List<Integer> list) {
long startTime = System.nanoTime();

// Perform sequential access using iterator


Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
int element = iterator.next();
}

return System.nanoTime() - startTime;


}

// Method to demonstrate optimal access strategy based on RandomAccess interface


private static void accessList(List<Integer> list) {
if (list instanceof RandomAccess) {
System.out.println("Using Random Access strategy (for loop)");
for (int i = 0; i < list.size(); i++) {
int element = list.get(i);
}
} else {
System.out.println("Using Sequential Access strategy (iterator)");
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
int element = iterator.next();
}
}
}

public static void main(String[] args) {


// Create ArrayList (implements RandomAccess)
List<Integer> arrayList = new ArrayList<>();
// Create LinkedList (does not implement RandomAccess)
List<Integer> linkedList = new LinkedList<>();

// Populate both lists with same data


for (int i = 0; i < 100000; i++) {
arrayList.add(i);
linkedList.add(i);
}

System.out.println("Testing ArrayList (implements RandomAccess):");


System.out.println("Is RandomAccess? " + (arrayList instanceof RandomAccess));

// Measure access times for ArrayList


long arrayListRandomTime = measureRandomAccessTime(arrayList);
long arrayListIteratorTime = measureIteratorAccessTime(arrayList);

System.out.println("Random access time: " + arrayListRandomTime + " ns");


System.out.println("Iterator access time: " + arrayListIteratorTime + " ns");

System.out.println("\nTesting LinkedList (does not implement RandomAccess):");


System.out.println("Is RandomAccess? " + (linkedList instanceof RandomAccess));

// Measure access times for LinkedList


long linkedListRandomTime = measureRandomAccessTime(linkedList);
long linkedListIteratorTime = measureIteratorAccessTime(linkedList);

System.out.println("Random access time: " + linkedListRandomTime + " ns");


System.out.println("Iterator access time: " + linkedListIteratorTime + " ns");

System.out.println("\nDemonstrating optimal access strategy:");


System.out.println("For ArrayList:");
accessList(arrayList);
System.out.println("For LinkedList:");
accessList(linkedList);

// Demonstrate practical usage with Collections method


System.out.println("\nBinary Search Performance:");
// Sort lists first (required for binary search)
Collections.sort(arrayList);
Collections.sort(linkedList);

long startTime = System.nanoTime();


Collections.binarySearch(arrayList, 50000);
System.out.println("ArrayList binary search time: " +
(System.nanoTime() - startTime) + " ns");

startTime = System.nanoTime();
Collections.binarySearch(linkedList, 50000);
System.out.println("LinkedList binary search time: " +
(System.nanoTime() - startTime) + " ns");
}
}

o/p

Testing ArrayList (implements RandomAccess):


Is RandomAccess? true
Random access time: 14488283 ns
Iterator access time: 15545606 ns

Testing LinkedList (does not implement RandomAccess):


Is RandomAccess? false
Random access time: 6491496468 ns
Iterator access time: 18176749 ns

Demonstrating optimal access strategy:


For ArrayList:
Using Random Access strategy (for loop)
For LinkedList:
Using Sequential Access strategy (iterator)

Binary Search Performance:


ArrayList binary search time: 211436 ns
LinkedList binary search time: 6191515 ns

19. Elucidate Legacy classes and interfaces with a suitable example program.

Vector:

Thread-safe implementation of a dynamic array


Similar to ArrayList but synchronized
Key methods:
addElement(): Adds element
elements(): Returns Enumeration
capacity(): Returns current capacity
trimToSize(): Trims capacity to size

Hashtable:

Thread-safe implementation of a hash table


Similar to HashMap but synchronized
Does not allow null keys or values
Key methods:

put(): Adds key-value pair


get(): Retrieves value
keys(): Returns Enumeration of keys

Dictionary:

Abstract class that maps keys to values


Superclass of Hashtable
Largely replaced by Map interface
Key methods:

put(): Adds mapping


get(): Retrieves value
keys(): Returns key Enumeration

Stack:

LIFO (Last-In-First-Out) data structure


Extends Vector
Key methods:

push(): Adds element


pop(): Removes and returns top element
peek(): Views top element

Properties:

Extends Hashtable
Used for storing configuration settings
Key methods:

setProperty(): Sets property


getProperty(): Gets property value
propertyNames(): Returns property names
BitSet:

Vector of bits that grows as needed


Used for flags and small sets
Key methods:

set(): Sets bit


clear(): Clears bit
get(): Checks bit status

Enumeration Interface:

Legacy iterator interface


Replaced by Iterator interface
Key methods:

hasMoreElements(): Checks for more elements


nextElement(): Gets next element

Important Notes:

These classes are considered legacy but still supported for backward compatibility
Modern alternatives are generally preferred:

ArrayList instead of Vector


HashMap instead of Hashtable
Iterator instead of Enumeration
LinkedList or ArrayDeque instead of Stack

Key differences from modern collections:

Legacy classes are synchronized (thread-safe)


Generally have poorer performance
Less functionality than modern alternatives
More restrictive (e.g., no null values in Hashtable)

Program

package Collections;
import java.util.*;

public class LegacyCollectionsDemo {


public static void main(String[] args) {
// 1. Vector demonstration
System.out.println("1. Vector Example:");
Vector<String> vector = new Vector<>();
vector.addElement("First");
vector.addElement("Second");
vector.addElement("Third");

// Using Enumeration to iterate Vector


System.out.println("\nUsing Enumeration to iterate Vector:");
Enumeration<String> enumeration = vector.elements();
while (enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());
}

// Vector specific methods


System.out.println("\nVector size: " + vector.size());
System.out.println("Vector capacity: " + vector.capacity());
vector.trimToSize();
System.out.println("Vector capacity after trim: " + vector.capacity());

// 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");

// Using Enumeration to iterate Hashtable keys


System.out.println("\nHashtable keys using Enumeration:");
Enumeration<Integer> keys = hashtable.keys();
while (keys.hasMoreElements()) {
Integer key = keys.nextElement();
System.out.println("Key: " + key + ", Value: " + hashtable.get(key));
}

// 3. Dictionary demonstration (Hashtable extends Dictionary)


System.out.println("\n3. Dictionary Example:");
Dictionary<Integer, String> dictionary = new Hashtable<>();
dictionary.put(1, "First");
dictionary.put(2, "Second");

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:

Using Enumeration to iterate Vector:


First
Second
Third

Vector size: 3
Vector capacity: 10
Vector capacity after trim: 3

2. Hashtable Example:

Hashtable keys using Enumeration:


Key: 3, Value: Three
Key: 2, Value: Two
Key: 1, Value: One

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)

You might also like