0% found this document useful (0 votes)
7 views32 pages

Module 1 Java Revision

The document provides an overview of the Java Collections Framework, detailing its interfaces such as Collection, List, SortedSet, and Queue, along with their methods and examples. It also discusses the use of user-defined classes in collections, the Comparator interface for custom sorting, and various collection classes like ArrayList, HashSet, and TreeSet. Additionally, it includes example programs demonstrating the creation and manipulation of collections, as well as constructors of the HashSet class.

Uploaded by

xdnik76
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views32 pages

Module 1 Java Revision

The document provides an overview of the Java Collections Framework, detailing its interfaces such as Collection, List, SortedSet, and Queue, along with their methods and examples. It also discusses the use of user-defined classes in collections, the Comparator interface for custom sorting, and various collection classes like ArrayList, HashSet, and TreeSet. Additionally, it includes example programs demonstrating the creation and manipulation of collections, as well as constructors of the HashSet class.

Uploaded by

xdnik76
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

MODULE 1

1. What are the various changes that collection framework underwent recently?(5M)

Sol.

2. List goals of framework.(4M)

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.

(i) Collection Interface:


The Collection interface is the root interface in the Java Collection Framework. It defines the
basic operations like adding, removing, and checking elements in a collection.

🔹 Method 1: add (E element) Adds an element to the collection.

 Syntax: Boolean add (E element)

 Example: collection.add("Java");

🔹 Method 2: addAll(Collection<? extends E> c)

 Definition: Adds all elements from another collection.

 Syntax: Boolean addAll(Collection<? extends E> c)

 Example: collection.addAll(otherCollection);

(ii) List Interface


The List interface represents an ordered collection (also called a sequence) that allows
duplicate elements and supports index-based access.

🔹 Method 1: add(int index, E element)

 Definition: Inserts the specified element at the specified position.

 Syntax: void add(int index, E element)

 Example: list.add(1, "Python");

🔹 Method 2: get(int index)

 Definition: Returns the element at the specified index.

 Syntax: E get(int index)

 Example: String lang = list.get(0);


(iii) SortedSet Interface
SortedSet is a subtype of Set that stores unique elements in ascending order.

🔹 Method 1: first() : Returns the first (lowest) element in the set.

 Syntax: E first()

 Example: E val = sortedSet.first();

🔹 Method 2: last() : Returns the last (highest) element in the set.

 Syntax: E last()

 Example: E val = sortedSet.last();

(iv) Queue Interface


The Queue interface represents a First-In-First-Out (FIFO) collection used to hold and
process elements.

🔹 Method 1: offer(E e)

 Definition: Inserts an element into the queue; returns false if the queue is full.

 Syntax: boolean offer(E e)

 Example: queue.offer("Task1");

🔹 Method 2: poll()

 Definition: Retrieves and removes the head of the queue; returns null if empty.

 Syntax: E poll()

 Example: String task = queue.poll();


4. Demonstrate linked lists for collection with examples.(7M)

Sol.

5. With an example program, explain how to store user-defined classes in collections.(10M)


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.

To store objects in a collection:

1. Define your custom class with some attributes and a constructor.


2. Create a collection to hold those objects.
3. Use add() to insert objects into the collection.
4. Use a loop or iterator to retrieve/display them.
🔹 Why Use Collections for User-Defined Classes?

 Collections like ArrayList allow dynamic storage and resizing.

 Easy to traverse, sort, and search through custom objects.

 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

● Comparator is a generic interface used to define custom ordering for objects.

Declaration:
interface Comparator<T>

● T specifies the type of objects that are to be compared.

Key Methods in Comparator Interface:

1. int compare(T obj1, T obj2)

● Compares two objects obj1 and obj2.

● Returns:

○ 0 → if both objects are equal.


○ Positive value → if obj1 is greater than obj2.
○ Negative value → if obj1 is less than obj2.

● Throws ClassCastException if the types are incompatible for comparison.

● This method can be overridden to define custom or reverse sorting orders.

2. boolean equals(Object obj)

● Tests if the given obj is equal to the invoking comparator.

● Returns:

○ true → if both are Comparator objects and use the same ordering.
○ false → otherwise.

Usage:

● By overriding compare(), you can:

○ Sort objects in custom order.


○ Reverse the natural order of sorting.
○ Implement complex sorting logic (e.g., multi-field comparison).

Program to Sort Accounts by Last Name Using Comparator

import java.util.*;

// Account class with first and last name


class Account {
String firstName;
String lastName;
String accountNumber;

// Constructor
Account(String firstName, String lastName, String accountNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.accountNumber = accountNumber;
}

// toString() for display


public String toString() {
return firstName + " " + lastName + " - " + accountNumber;
}
}

// Comparator to sort by last name


class LastNameComparator implements Comparator<Account> {
public int compare(Account a1, Account a2) {
return a1.lastName.compareToIgnoreCase(a2.lastName);
}
}

public class SortAccounts {


public static void main(String[] args) {
// Create list of accounts
List<Account> accounts = new ArrayList<>();
accounts.add(new Account("John", "Smith", "ACC001"));
accounts.add(new Account("Alice", "Brown", "ACC002"));
accounts.add(new Account("Bob", "Davis", "ACC003"));
accounts.add(new Account("Zara", "Anderson", "ACC004"));

// Before sorting
System.out.println("Before sorting:");
for (Account acc : accounts) {
System.out.println(acc);
}

// Sort using Comparator


Collections.sort(accounts, new LastNameComparator());

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

(i) Linked List


(ii) Array List
(iii) Tree Set
(iv) Hash Set

Sol. (sol taken from pdf, formatted by chatgpt)

Linked list is explained in Q4

ArrayList in Java

● ArrayList class extends AbstractList and implements the List interface.


● It is a generic class with this declaration:
class ArrayList<E>
● It uses a resizable array to store elements.

Constructors of ArrayList

1. ArrayList()
Creates an empty ArrayList.

2. ArrayList(Collection<? extends E> c)


Creates an ArrayList initialized with elements of collection c.

3. ArrayList(int capacity)
Creates an ArrayList with a specified initial capacity.
(Capacity grows automatically as new elements are added.)

Basic ArrayList Operations - example program

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

System.out.println("Size of al after additions: " + al.size());


System.out.println("Contents of al: " + al);

// Remove elements
al.remove("F");
al.remove(2);

System.out.println("Size of al after deletions: " + al.size());


System.out.println("Contents of al: " + al);
}
}

Output -

Initial size of al: 0


Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]

HashSet in Java

● HashSet extends AbstractSet and implements the Set interface.

● It uses a hash table for storage.

● It belongs to the java.util package.

Key Points about HashSet

● Stores elements using hashing mechanism.

● Only unique elements are allowed (no duplicates).

● Unordered: The elements are not stored in insertion order.

It is a generic class, declared as:

class HashSet<E>

● Here, E is the type of elements the set will hold.


Constructors of HashSet
Constructor Description

HashSet() Creates an empty HashSet.

HashSet(Collection<? extends E> c) Creates a HashSet containing elements from the


given collection.

HashSet(int capacity) Creates a HashSet with the specified initial


capacity.

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

● TreeSet extends AbstractSet and implements the NavigableSet interface.

● It uses a Red-Black Tree structure to store elements.

● **Objects are stored in sorted, ascending order automatically.

● Ideal for storing large, sorted datasets with fast access and retrieval.
Key Features of TreeSet

● Maintains elements in ascending sorted order.

● Does not allow duplicate elements.

● Access time is faster than HashSet for sorted elements.

It is a generic class, declared as:

class TreeSet<E>

● Here, E is the type of objects the set will hold.

Constructors of TreeSet

Constructor Description

TreeSet() Constructs an empty tree set.

TreeSet(Collection<? extends E> c) Initializes with elements of a collection.

TreeSet(Comparator<? super E> comp) Uses a custom comparator to order


elements.

TreeSet(SortedSet<E> ss) Initializes with elements from a sorted set.

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]

9. Explain the constructors of HashSet class with an example.(10M)


Sol.

The HashSet class provides four constructors:

Constructor Description

HashSet() Creates a default empty HashSet with initial capacity


16 and load factor 0.75.

HashSet(Collection<? extends Creates a HashSet with elements from the specified


E> c) collection.

HashSet(int capacity) Creates an empty HashSet with the specified initial


capacity.

HashSet(int capacity, float Creates an empty HashSet with the given initial
fillRatio) capacity and load factor.
1. HashSet() – Default Constructor

import java.util.*;

public class DefaultConstructorExample {


public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Mango");

System.out.println("HashSet: " + set);


}
}

Explanation: Uses default capacity (16) and load factor (0.75).

2. HashSet(Collection<? extends E> c)

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

System.out.println("HashSet from List: " + set);


}
}

Explanation: Removes duplicate "Red" and creates a set with unique elements from the list.

3. HashSet(int capacity)

import java.util.*;

public class CapacityConstructorExample {


public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>(50); // Initial capacity of 50
set.add(1);
set.add(2);
set.add(3);

System.out.println("HashSet with capacity 50: " + set);


}
}

Explanation: Initializes the set with space for 50 elements. Capacity expands when needed.

4. HashSet(int capacity, float fillRatio)

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.

The ArrayList in Java is needed for the following reasons:

1. Dynamic Sizing:
Unlike arrays, ArrayList can grow or shrink dynamically at runtime based on the
number of elements.

2. Ease of Use & Utility Methods:


It provides built-in methods (like add(), remove(), contains(), clear(), etc.) for
easy manipulation of data without manual index handling.

13. Implement a java program to demonstrate creating an Arraylist, adding elements,


removing elements, sorting elements of ArrayList.(8M)
Sol.
import java.util.*;

public class ArrayListDemo {


public static void main(String[] args) {
// Creating an ArrayList of Strings
ArrayList<String> fruits = new ArrayList<String>();

// Adding elements to the ArrayList


fruits.add("Banana");
fruits.add("Apple");
fruits.add("Mango");
fruits.add("Orange");

// Displaying the ArrayList


System.out.println("Original ArrayList: " + fruits);

// Removing an element
fruits.remove("Mango");

// Displaying after removal


System.out.println("After removing 'Mango': " + fruits);

// Sorting the ArrayList in ascending order


Collections.sort(fruits);

// Displaying sorted list


System.out.println("Sorted ArrayList: " + fruits);
}
}

Output -

Original ArrayList: [Banana, Apple, Mango, Orange]


After removing 'Mango': [Banana, Apple, Orange]
Sorted ArrayList: [Apple, Banana, Orange]

14. Explain the following methods of ArrayList: (8M)


(i) binarysearch
(ii) copy
(iii) equals
(iv) fills

Sol.

(i) Collections.binarySearch()

● Purpose: Searches for a specified element in a sorted ArrayList.

Syntax
int index = Collections.binarySearch(list, key);

● Returns:
○ Index of the element if found.
○ If not found, returns (-(insertion point) - 1).
Example:

ArrayList<String> list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Mango"));


Collections.sort(list);
int index = Collections.binarySearch(list, "Banana"); // returns 1

(ii) Collections.copy()

● Purpose: Copies elements from one list to another.

Syntax:
Collections.copy(destList, sourceList);

● Note: destList must be at least as long as sourceList.

Example:

List<String> source = Arrays.asList("A", "B", "C");


List<String> dest = new ArrayList<>(Arrays.asList("X", "Y", "Z"));
Collections.copy(dest, source); // dest becomes [A, B, C]

(iii) equals()

● Purpose: Compares two ArrayLists for equality of contents and order.

Syntax:
boolean result = list1.equals(list2);

● Returns: true if both lists contain the same elements in the same order, otherwise false.

Example:

ArrayList<Integer> a = new ArrayList<>(Arrays.asList(1, 2, 3));


ArrayList<Integer> b = new ArrayList<>(Arrays.asList(1, 2, 3));
System.out.println(a.equals(b)); // true

(iv) Collections.fill()

● Purpose: Replaces all elements in a list with a single specified value.

Syntax:
Collections.fill(list, value);
Example:

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));


Collections.fill(list, "X"); // list becomes [X, X, X]
15. Implement a java linked list collection of strings to demonstrate functionalities of
add(), addFirst(), addLast() and remove element from specified position.(8M)

Sol.

import java.util.*;

class LinkedListDemo {
public static void main(String[] args) {
// Create a LinkedList of Strings
LinkedList<String> list = new LinkedList<>();

// add(): Add elements to the end of the list


list.add("Apple");
list.add("Banana");
list.add("Cherry");

// Display list after using add()


System.out.println("List after add(): " + list);

// addFirst(): Add element at the beginning


list.addFirst("Mango");
System.out.println("List after addFirst(): " + list);

// addLast(): Add element at the end


list.addLast("Orange");
System.out.println("List after addLast(): " + list);

// remove(index): Remove element at position 2 (third element)


list.remove(2);
System.out.println("List after removing element at index 2: " + list);
}
}

Output -

List after add(): [Apple, Banana, Cherry]


List after addFirst(): [Mango, Apple, Banana, Cherry]
List after addLast(): [Mango, Apple, Banana, Cherry, Orange]
List after removing element at index 2: [Mango, Apple, Cherry, Orange]
16. Explain the following map classes: (8M)
(i) HashMap (ii) TreeMap

Sol.
import java.util.*;

class HashMapDemo {
public static void main(String args[]) {
// Create a HashMap
HashMap<String, Double> hm = new HashMap<String, Double>();

// Put key-value pairs into the map


hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Tod Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));

// Get a set of the entries


Set<Map.Entry<String, Double>> set = hm.entrySet();

// Display the set


for (Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}

System.out.println();

// Deposit 1000 into John Doe's account


double balance = hm.get("John Doe");
hm.put("John Doe", balance + 1000);

System.out.println("John Doe's new balance: " + hm.get("John Doe"));


}
}

Output -

Ralph Smith: -19.08


Tom Smith: 123.22
John Doe: 3434.34
Tod Hall: 99.22
Jane Baker: 1378.0

John Doe's new balance: 4434.34


import java.util.*;

class TreeMapDemo {
public static void main(String args[]) {
// Create a TreeMap
TreeMap<String, Double> tm = new TreeMap<String, Double>();

// Put elements into the map


tm.put("John Doe", new Double(3434.34));
tm.put("Tom Smith", new Double(123.22));
tm.put("Jane Baker", new Double(1378.00));
tm.put("Tod Hall", new Double(99.22));
tm.put("Ralph Smith", new Double(-19.08));

// Get a set of the entries


Set<Map.Entry<String, Double>> set = tm.entrySet();
// Display the elements
for (Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}

System.out.println();

// Update balance for John Doe


double balance = tm.get("John Doe");
tm.put("John Doe", balance + 1000);

System.out.println("John Doe's new balance: " + tm.get("John Doe"));


}
}

Output -

Jane Baker: 1378.0


John Doe: 3434.34
Ralph Smith: -19.08
Tod Hall: 99.22
Tom Smith: 123.22

John Doe's new balance: 4434.34

17. Mention and explain different interfaces that support maps.(6M)

Sol.

The Map Interfaces

The Java Collections Framework provides several interfaces to support maps, each serving a
distinct purpose.

1. Map Interface

● Definition: The Map<K, V> interface maps unique keys to values.

Declaration:

interface Map<K, V>

○ K: Type of keys
○ V: Type of values
● Core Operations:

○ put(K key, V value): Inserts a value associated with a key.


○ V get(Object key): Retrieves a value based on the key.

● Collection Views:

○ entrySet(): Returns a Set view of all map entries.


○ keySet(): Returns a Set view of all keys.
○ values(): Returns a Collection view of all values.

● Exceptions:

○ ClassCastException: Incompatible object types.


○ NullPointerException: If nulls are not permitted.
○ UnsupportedOperationException: For unmodifiable maps.
○ IllegalArgumentException: If an invalid argument is used.

❗ Maps do not extend the Collection interface, but support integration via
collection-views.

2. SortedMap Interface

● Definition: Extends Map, maintains entries in ascending key order.

Declaration:

interface SortedMap<K, V>

● Key Methods:

○ firstKey(): Returns the first key.


○ lastKey(): Returns the last key.
○ headMap(K toKey): Returns a view of the map with keys less than toKey.
○ tailMap(K fromKey): Returns a view with keys ≥ fromKey.
○ subMap(K fromKey, K toKey): Keys between fromKey and toKey.

● Exceptions:

○ NoSuchElementException: When no elements exist.


○ ClassCastException, NullPointerException,
IllegalArgumentException.
3. NavigableMap Interface

● Definition: Added in Java 6. Extends SortedMap and allows navigation based on


closest matches to keys.

Declaration:

interface NavigableMap<K, V>

● Enhancements Over SortedMap:

○ lowerKey(K key), higherKey(K key)


○ ceilingKey(K key), floorKey(K key)
○ pollFirstEntry(), pollLastEntry()
○ descendingMap(): Returns a reverse-order view.

● Exceptions:

○ Same as in SortedMap.

4. Map.Entry Interface

● Definition: Represents a key-value pair inside a map.

● Obtained From: entrySet() method of the Map interface.

Declaration:

interface Map.Entry<K, V>

● Methods:

○ K getKey(): Returns the key.


○ V getValue(): Returns the value.
○ V setValue(V value): Replaces the value.

Used for iterating over map entries efficiently.


18. What are legacy classes? Explain any four legacy classes of Java’s collection
Framework with suitable program.(10M)

Sol.

Legacy Classes in Java:


Legacy classes in Java are pre-collection classes introduced before the Java Collection
Framework (JDK 1.2). They were later retrofitted to work with collections but are still part of the
Java API for backward compatibility.

 Synchronized by Default: Unlike modern collections, legacy classes are thread-


safe (but slower due to synchronization overhead).
 Modern Replacements:
 Vector → ArrayList (or Collections.synchronizedList())
 Hashtable → HashMap (or ConcurrentHashMap)
 Stack → ArrayDeque (more efficient for LIFO operations)

The Four legacy classes –

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

🔹 Syntax: class Vector<E>

Where E is the type of elements stored.

🔹 Example:

Vector<String> names = new Vector<>();

names.add("Java");

names.add("Python");

System.out.println(names);

2. Stack :Stack is a subclass of Vector that represents a Last-In-First-Out (LIFO) data


structure. It uses methods like push(), pop(), and peek() to manipulate the stack.

🔹 Syntax: class Stack<E>

Where E is the element type in the stack.

🔹 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.

🔹 Syntax: class Dictionary<K, V>

Where K is the key type and V is the value type.

🔹 Example:

// Dictionary is abstract, so used via Hashtable

Dictionary<Integer, String> dict = new Hashtable<>();

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.

🔹 Syntax: class Hashtable<K, V>

🔹 Example:

Hashtable<Integer, String> ht = new Hashtable<>();

ht.put(101, "Alice");

ht.put(102, "Bob");

System.out.println(ht.get(101)); // Alice

1. Vector Example
import java.util.Vector;

public class VectorExample {


public static void main(String[] args) {
Vector<String> vector = new Vector<String>();
vector.add("Apple");
vector.add("Banana");
vector.add("Mango");

System.out.println("Vector Elements: " + vector);


vector.remove("Banana");
System.out.println("After removing Banana: " + vector);
System.out.println("First Element: " + vector.get(0));
}
}

2. Stack Example

import java.util.Stack;

public class StackExample {


public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(10);
stack.push(20);
stack.push(30);

System.out.println("Stack Elements: " + stack);


System.out.println("Top Element (peek): " + stack.peek());
System.out.println("Popped Element: " + stack.pop());
System.out.println("Stack after pop: " + stack);
System.out.println("Is Stack Empty? " + stack.empty());
}
}

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

System.out.println("Value for key 2: " + dict.get(2));


System.out.println("All Values:");
for (int key = 1; key <= 3; key++) {
System.out.println("Key " + key + ": " + dict.get(key));
}
}
}

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

You might also like