UNIT 4: Java Collection Framework
AKTU Semester Exam — Complete Study Notes with Code & PYQ Programs
1. FRAMEWORK & COLLECTION FRAMEWORK
1.1 What is a Framework?
A framework is a readymade architecture where everything is predefined. In software development, a
framework is a set of predefined classes and interfaces that help build programs quickly.
📝 Exam Tip: Framework = readymade architecture with predefined classes + interfaces
1.2 Collection Framework — Definition
The Java Collection Framework is a set of predefined classes and interfaces that are used to store and
manipulate a group of objects (data, list, objects, etc.) in object form.
➤ Contains: set of algorithms (sort, search, etc.)
➤ Used to implement: collection (data, object, list etc.) in object form
➤ Package: [Link]
1.3 Hierarchy of Collection Framework
The collection framework is organized as:
Iterable (Interface)
└── Collection (Interface)
├── List (Interface)
│ ├── ArrayList (Class)
│ ├── LinkedList (Class)
│ └── Vector (Class)
│ └── Stack (Class)
├── Queue (Interface)
│ ├── PriorityQueue (Class)
│ └── Deque (Interface)
│ └── ArrayDeque (Class)
└── Set (Interface)
├── HashSet (Class)
├── LinkedHashSet (Class)
└── SortedSet (Interface)
└── TreeSet (Class)
2. KEY INTERFACES
2.1 Collection Interface
The Collection interface is the interface which is implemented by all the classes in the collection framework. It
declares the methods that every collection will have. In other words, it builds the foundation on which the
collection framework depends.
Some key methods of Collection interface:
➤ boolean add(Object obj): inserts an element
➤ boolean addAll(Collection c): adds all elements of c
➤ void clear(): removes all elements
➤ boolean remove(Object o): removes the given element
➤ int size(): returns total number of elements
➤ boolean contains(Object o): searches an element
➤ boolean isEmpty(): checks if collection is empty
➤ Iterator iterator(): returns an iterator
📝 Exam Tip: Collection interface = foundation of entire Java Collection Framework
2.2 Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection interface extends Iterable
interface, so all subclasses of Collection also implement Iterable.
➤ Contains only one method: Iterator<T> iterator()
➤ Purpose: returns the iterator over elements of type T, used for for-each loop
3. ARRAYLIST
3.1 Definition
ArrayList is used to create a Dynamic Array. An ArrayList object is a collection of object elements. It is used when
the size of the array is not known in advance.
3.2 Key Properties
➤ Dynamic Array: grows and shrinks automatically — no size limit
➤ Cannot store primitive types: use wrapper classes (Integer, Double, etc.) — it is type-safe
➤ Maintains insertion order: elements are retrieved in the order they were added
➤ Allows duplicates: same value can appear multiple times
➤ Not synchronized: not thread-safe
➤ Random access: works on index basis, so access is fast
➤ Cannot store primitives: use Integer, Float, Character, etc. instead of int, float, char
➤ Found in: [Link] package
➤ From JDK 1.5+: ArrayList is a generic class
3.3 Class Hierarchy
Iterable → Collection → List → AbstractList → ArrayList
3.4 Syntax / Declaration
ArrayList<ObjectType> arrayListObject = new ArrayList<ObjectType>();
Example:
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
3.5 Full Class Declaration
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
3.6 Basic Example with Code
import [Link].*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
[Link]("Rohan");
[Link]("Mohan");
[Link]("Sohan");
[Link](al);
}
}
Output: [Rohan, Mohan, Sohan]
3.7 Traversing ArrayList — 3 Ways
(i) Using for loop
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i) + " ");
}
Output: Rohan Mohan Sohan
(ii) Using for-each loop
for (String s : al) {
[Link](s + " ");
}
Output: Rohan Mohan Sohan
(iii) Using Iterator
Iterator<String> itr = [Link]();
while ([Link]()) {
[Link]([Link]());
}
Output: Rohan
Mohan
Sohan
3.8 Iterator Interface — 3 Methods
➤ public boolean hasNext(): returns true if more elements exist
➤ public Object next(): returns the next element
➤ public void remove(): removes the current element
📝 Exam Tip: Iterator moves only in FORWARD direction (one way only)
3.9 ArrayList vs LinkedList (Comparison Table)
Feature ArrayList LinkedList
Internal Storage Dynamic Array Doubly Linked List
Manipulation Speed Slow (shifting needed) Fast (no shifting needed)
Memory Location Contiguous Non-contiguous
Access Type Random (index-based) Sequential
Default Capacity 10 No default capacity
Acts as List only List + Queue both
Can traverse as Iterator only Iterator + ListIterator
3.10 ArrayList vs Vector (Comparison Table)
Feature ArrayList Vector
Synchronized No (not thread-safe) Yes (thread-safe)
Speed Fast Slow
Growth Rate 50% of current size 100% (doubles)
Legacy Class No (JDK 1.2) Yes
Traversal Iterator only Iterator + Enumeration
📝 Exam Tip: PYQ Favourite: Difference between ArrayList, LinkedList and Vector — memorize this table!
🎯 PYQ: Write a Java program to create an ArrayList of Employee objects and display them using Iterator.
4. LINKEDLIST
4.1 Definition
LinkedList implements the Collection List interface. It uses a doubly linked list internally to store the elements.
Manipulation is fast because no shifting is required when elements are added/removed.
4.2 Key Properties
➤ Uses doubly linked list internally: each node has data + next + previous pointer
➤ Can store duplicate elements: allows repeated values
➤ Maintains insertion order: elements stay in order of insertion
➤ Not synchronized: not thread-safe
➤ Manipulation is fast: no shifting needed unlike ArrayList
➤ Can act as List + Queue both: implements List and Deque interfaces
4.3 Code Example
import [Link].*;
public class TestJavaCollection {
public static void main(String args[]) {
LinkedList<String> al = new LinkedList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi"); // duplicate allowed
[Link]("Ajay");
Iterator<String> itr = [Link]();
while ([Link]()) {
[Link]([Link]());
}
}
}
Output: Ravi
Vijay
Ravi
Ajay
5. LIST ITERATOR
5.1 Definition
The ListIterator is also an interface that belongs to [Link] package. It extends the Iterator<E> interface. It
allows us to iterate over the List in BOTH forward and backward direction (unlike Iterator which is forward only).
5.2 Key Methods
➤ hasNext(): returns true if there is a next element
➤ next(): returns the next element (forward direction)
➤ hasPrevious(): returns true if there is a previous element
➤ previous(): returns the previous element (backward direction)
➤ remove(): removes the current element
📝 Exam Tip: ListIterator = bidirectional iterator (forward + backward). Iterator = only forward.
5.3 Code Example
import [Link].*;
public class IterateList {
public static void main(String args[]) {
List<String> city = [Link]("Boston", "San Diego", "Las Vegas");
ListIterator<String> listIterator = [Link]();
while ([Link]()) {
[Link]([Link]());
}
}
}
Output: Boston
San Diego
Las Vegas
6. VECTOR
6.1 Definition
Vector is a part of the Java Collection Framework. It uses a dynamic array to store the data elements. It is similar
to ArrayList. However, it is synchronized (thread-safe) and contains many legacy methods that are not part of
the Collection framework.
6.2 Key Properties
➤ Synchronized: thread-safe (one thread at a time)
➤ Legacy class: introduced before Collection Framework
➤ Generic and non-generic: can be used with or without generics
➤ Growth: doubles its size (100%) when capacity is exceeded
➤ Slow: because of synchronization overhead
➤ Traversal: can use both Iterator and Enumeration
6.3 Code Example
import [Link].*;
class VectorExample {
public static void main(String args[]) {
Vector<String> vc = new Vector<>();
[Link]("HTML");
[Link]("DHTML");
[Link]("XHTML");
[Link](vc);
[Link]("DHTML");
[Link](vc);
}
}
Output: [HTML, DHTML, XHTML]
[HTML, XHTML]
7. STACK
7.1 Definition
Stack is a subclass of Vector. It implements the LIFO (Last In First Out) data structure. The Stack class contains all
the methods of the Vector class and also provides its own methods like push(), pop(), peek(), isEmpty(), and
search().
7.2 Key Properties
➤ LIFO: Last In First Out — last element added is first to be removed
➤ Subclass of Vector: inherits all Vector methods
➤ push(): adds element to top of stack
➤ pop(): removes and returns top element
➤ peek(): returns top element WITHOUT removing it
➤ isEmpty(): returns true if stack is empty
➤ search(): returns position of element from top
7.3 Code Example
import [Link].*;
class StackExample {
public static void main(String argv[]) {
Stack<Integer> st = new Stack<Integer>();
[Link]([Link]()); // true
[Link](12);
[Link](21);
[Link](18);
[Link](st); // [12, 21, 18]
[Link]([Link]()); // false
[Link]([Link]()); // 18 (top element)
[Link](); // removes 18
[Link](st); // [12, 21]
[Link]([Link]()); // 21
}
}
Output: true → [12,21,18] → false → 18 → [12,21] → 21
8. QUEUE INTERFACE
8.1 Definition
Queue interface maintains the FIFO (First In First Out) order. It can be defined as an ordered list that is used to
hold the elements which are about to be processed by their priorities.
8.2 Key Properties
➤ FIFO: First In First Out — element added first is removed first
➤ PriorityQueue: does NOT allow null values
➤ Implementations: PriorityQueue, ArrayDeque
8.3 Important Methods
➤ add() / offer(): to add element
➤ remove() / poll(): to remove element (from front)
➤ element() / peek(): to get head element without removing
📝 Exam Tip: remove() throws exception if queue is empty; poll() returns null — remember this difference!
8.4 PriorityQueue — Definition
The PriorityQueue class implements the Queue interface. It holds elements which are to be processed by their
priorities. PriorityQueue does NOT allow null values to be stored in the queue. Elements are ordered by natural
ordering or by a Comparator.
8.5 PriorityQueue Code Example
import [Link].*;
public class TestJavaCollection5 {
public static void main(String args[]) {
PriorityQueue<String> queue = new PriorityQueue<String>();
[Link]("Amit Sharma");
[Link]("Vijay Raj");
[Link]("JaiShankar");
[Link]("Raj");
[Link]("Head: " + [Link]());
[Link]("Head: " + [Link]());
[Link]("Iterating:");
Iterator itr = [Link]();
while ([Link]()) {
[Link]([Link]());
}
[Link]();
[Link]();
[Link]("After removing two: " + queue);
}
}
Output: Head: Amit Sharma
Iterating: Amit Sharma, Raj, JaiShankar, Vijay Raj
After removing two: [JaiShankar, Vijay Raj]
9. DEQUE INTERFACE & ARRAYDEQUE
9.1 Deque Interface — Definition
Deque interface extends the Queue interface. In Deque, we can remove and add the elements from both the
sides. Deque stands for double-ended queue, which enables us to perform operations at both ends (front and
rear).
Deque d = new ArrayDeque();
9.2 ArrayDeque — Definition
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can add
or delete the elements from both the ends. ArrayDeque is faster than ArrayList and Stack and has no capacity
restrictions.
9.3 Key Properties
➤ Faster than ArrayList and Stack: no capacity restrictions
➤ Add/delete from both ends: unlike normal Queue (only from rear)
➤ Does not allow null: null elements not permitted
9.4 Code Example
import [Link].*;
public class TestJavaCollection6 {
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<String>();
[Link]("Gautam");
[Link]("Karan");
[Link]("Ajay");
for (String str : deque) {
[Link](str);
}
}
}
Output: Gautam
Karan
Ajay
10. SET INTERFACE — HashSet, LinkedHashSet, TreeSet
10.1 HashSet — Definition
HashSet extends AbstractSet class and implements Set, Cloneable, Serializable interfaces. It works on a hash
table. It is one of the most commonly used implementations of the Set interface.
10.2 HashSet Key Properties
➤ NOT allowed duplicate elements: automatically ignores duplicates
➤ Allows ONE null value: only one null is allowed
➤ Does NOT maintain insertion order: elements stored by their hash values
➤ Non-synchronized: not thread-safe
➤ Operations: removeAll, addAll, retainAll, contains
10.3 HashSet Code Example
import [Link].*;
class HashSetDemo {
public static void main(String argv[]) {
HashSet<String> hs = new HashSet<String>();
[Link]("LKO");
[Link]("KNP");
[Link]("GKP");
[Link]("LKO"); // duplicate - will be ignored
Iterator<String> itr = [Link]();
while ([Link]())
[Link]([Link]());
}
}
Output: KNP, GKP, LKO (order may vary - no insertion order)
10.4 LinkedHashSet — Definition
LinkedHashSet extends HashSet class and implements Set, Cloneable, Serializable interfaces. It is similar to
HashSet but MAINTAINS insertion order (unlike HashSet).
10.5 LinkedHashSet Key Properties
➤ NOT allowed duplicate elements: same as HashSet
➤ Allows null value: one null allowed
➤ Maintains insertion order: unlike HashSet — this is the main difference
➤ Non-synchronized: not thread-safe
10.6 Difference: HashSet vs LinkedHashSet
Feature HashSet LinkedHashSet
Insertion Order Not maintained Maintained
Internal Structure Hash table Hash table + Linked List
Performance Slightly faster Slightly slower
Null Value Allowed (one) Allowed (one)
Duplicates Not allowed Not allowed
11. TREESET
11.1 Definition
TreeSet extends AbstractSet class and implements List, SortedTree, NavigableSet interfaces. It stores elements
in sorted (ascending) order automatically.
11.2 Key Properties
➤ Allows only unique elements: like HashSet class
➤ Does NOT allow null value: NullPointerException if null added
➤ Non-synchronized: not thread-safe
➤ Maintains ascending order: automatic natural sorting
➤ Access and retrieval is fast: uses balanced BST (Red-Black tree)
➤ Only generic types: that implement Comparable interface are allowed
➤ Self-balancing: implemented using Red-Black tree / Binary Search Tree
11.3 Important TreeSet Methods
➤ pollFirst(): deletes and returns first (smallest) element
➤ pollLast(): deletes and returns last (largest) element
➤ descendingSet(): returns elements in descending order
➤ headSet(e, boolean): returns elements less than e
➤ subSet(e1, b1, e2, b2): returns elements from e1 to e2
➤ tailSet(e, boolean): returns elements greater than or equal to e
11.4 TreeSet Code Example
import [Link].*;
class TreeSetDemo {
public static void main(String argv[]) {
TreeSet<Integer> ts = new TreeSet<Integer>();
[Link](18);
[Link](12);
[Link](21);
[Link](60);
[Link](55);
[Link](ts);
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
Output: [12, 18, 21, 55, 60]
pollFirst: 12
pollLast: 60
descendingSet: [55, 21, 18]
📝 Exam Tip: TreeSet always stores in ascending order. TreeSet does NOT allow null. HashSet allows one null.
🎯 PYQ: Differentiate between HashSet, LinkedHashSet and TreeSet with example programs.
12. SORTED SET INTERFACE
12.1 Definition
A SortedSet is used to provide a particular ordering on its elements. The elements are ordered either by using a
natural ordering or by using a Comparator. All elements inserted into a sorted set must implement the
Comparable interface. The set's iterator will traverse the set in ascending order.
12.2 Key Methods of SortedSet
➤ comparator(): returns the comparator used to order the set. Returns null if natural ordering is used
➤ first(): returns the first (smallest) element from the set
➤ last(): returns the last (largest) element from the set
➤ headSet(E toElement): returns a view of elements strictly less than toElement
➤ tailSet(E fromElement): returns a view of elements greater than or equal to fromElement
➤ subSet(E from, E to): returns elements from 'from' (inclusive) to 'to' (exclusive)
➤ spliterator(): returns a key-value mapping associated with greatest key less than or equal to given key
12.3 SortedSet Code Example
import [Link].*;
public class JavaSortedSetExample1 {
public static void main(String args[]) {
SortedSet set = new TreeSet();
[Link]("Audi");
[Link]("BMW");
[Link]("Mercedes");
[Link]("Baleno");
[Link]("Elements: " + set);
[Link]("First: " + [Link]());
[Link]("Last: " + [Link]());
[Link]("HeadSet (Baleno): " + [Link]("Baleno"));
[Link]("TailSet (Audi): " + [Link]("Audi"));
}
}
Output: Elements: [Audi, Baleno, BMW, Mercedes]
First: Audi
Last: Mercedes
HeadSet (Baleno): [Audi]
TailSet (Audi): [Audi, Baleno, BMW, Mercedes]
13. SET INTERFACE METHODS & OPERATIONS
13.1 Set Methods
➤ add(type element) → boolean: inserts new value. Returns false if already present, true if not
➤ addAll(Collection data) → boolean: appends all elements of specified collection to set (union)
➤ clear() → void: removes all elements from the set (does not delete reference)
➤ contains(Object element) → boolean: returns true if element is present, false if not
➤ hashCode() → int: returns the hash code value for the set
➤ iterator() → Iterator: returns iterator used to get elements one by one
13.2 Mathematical Operations on Set
Given: set1 = [22, 45, 33, 66, 55, 34, 77] and set2 = [33, 2, 83, 45, 3, 12, 55]
➤ Intersection (retainAll): elements present in BOTH sets → [33, 45, 55]
➤ Union (addAll): all elements of BOTH sets combined → [2, 3, 12, 22, 33, 34, 45, 55, 66, 77, 83]
➤ Difference (removeAll): elements in set1 NOT in set2 → [66, 34, 22, 77]
📝 Exam Tip: addAll() = Union, retainAll() = Intersection, removeAll() = Difference
14. COMPARABLE INTERFACE
14.1 Definition
Comparable interface is defined in [Link] package. It is used to sort the user-defined class's objects in a list. It
works on a single field (property of object) for example id, age, name, salary etc. It affects the original class (the
actual class is modified).
14.2 Key Points
➤ Package: [Link]
➤ Method: public int compareTo(Object ob)
➤ Works on: single field only (at least one field exists)
➤ Affects original class: actual class is modified
➤ Used with: [Link](list) method
14.3 compareTo() Rules
➤ Returns 0: if current object == specified object
➤ Returns 1 (positive): if current object > specified object
➤ Returns -1 (negative): if current object < specified object
14.4 Comparable vs Comparator
Feature Comparable Comparator
Package [Link] [Link]
Method compareTo(Object ob) compare(Object o1, Object o2)
Sorting Fields Single field (at least 1) Multiple fields (at least 2)
Affects Original Class? Yes (modified) No (doesn't affect original)
Sort Method [Link](list) [Link](list, comparator)
Sorting Sequences One sequence Multiple sequences
14.5 Comparable Code Example
class Emp implements Comparable<Emp> {
int id;
String name;
int salary;
Emp(int id, String name, int salary) {
[Link] = id;
[Link] = name;
[Link] = salary;
}
public int compareTo(Emp e) {
if (id == [Link]) return 0;
else if (id > [Link]) return 1;
else return -1;
}
}
class Test {
public static void main(String argv[]) {
Emp e1 = new Emp(101, "Sulabh", 4000);
Emp e2 = new Emp(100, "Rakesh", 3000);
Emp e3 = new Emp(102, "Aditya", 3500);
ArrayList<Emp> al = new ArrayList<Emp>();
[Link](e1); [Link](e2); [Link](e3);
[Link](al);
for (Emp e : al)
[Link]([Link] + " " + [Link] + " " + [Link]);
}
}
Output: 100 Rakesh 3000
101 Sulabh 4000
102 Aditya 3500
🎯 PYQ: Write a program to sort Employee objects by id using Comparable interface.
15. JAVA MAP INTERFACE & HASHMAP
15.1 Java Map Interface — Definition
A Map contains values on the basis of key-value pair. Each key and value pair is known as an entry. A map
contains unique keys. A map is useful if you have to search, update or delete elements on the basis of a key.
15.2 Map Hierarchy
Map (Interface)
├── SortedMap (Interface)
│ └── TreeMap (Class)
└── HashMap (Class)
└── LinkedHashMap (Class)
15.3 Map Key Rules
➤ Unique keys only: no duplicate keys allowed
➤ Duplicate values allowed: same value can have different keys
➤ HashMap + LinkedHashMap: allow null keys and null values
➤ TreeMap: does NOT allow any null key or value
➤ Cannot be traversed directly: must convert to Set using keySet() or entrySet()
15.4 HashMap — Definition
HashMap extends AbstractMap and implements Map interface. It works on the following two concepts:
➤ Key: a unique value that uniquely identifies the element
➤ Value: the object/value stored in the list with its associated key
HashMap allows only unique keys. If you try to insert a value with an existing key, it will REPLACE the value of
the existing key. It allows only ONE null key and multiple null values. It does not maintain order. It is non-
synchronized.
15.5 HashMap Syntax
public class HashMap<K,V> extends AbstractMap implements Map
where K = type of Key, V = type of Value/object
15.6 Methods of Map Interface
Method Description
V put(K key, V value) Used to insert an entry in the map
void putAll(Map map) Used to insert the specified map in the map
V remove(Object key) Used to delete an entry for the specified key
V putIfAbsent(K key, V value) Inserts only if key is not already specified
Set keySet() Returns Set view containing all the keys
void clear() Used to reset/clear the map
boolean containsValue(Object value) Returns true if value equal to given value exists
boolean equals(Object o) Used to compare specified object with the map
V get(Object key) Returns object that contains value associated with
the key
15.7 HashMap Code Example
import [Link].*;
class HashMapDemo {
public static void main(String argv[]) {
HashMap<Integer,String> hm = new HashMap<Integer,String>();
[Link](1, "SRGI");
[Link](2, "SRIMT");
[Link](3, "SRIBM");
[Link](hm);
[Link](3, "SRISA"); // replaces old value for key 3
[Link](hm);
[Link](4, "SR");
[Link](hm);
[Link](3);
[Link](hm);
}
}
Output: {1=SRGI, 2=SRIMT, 3=SRIBM}
{1=SRGI, 2=SRIMT, 3=SRISA}
{1=SRGI, 2=SRIMT, 3=SRISA, 4=SR}
{1=SRGI, 2=SRIMT, 4=SR}
16. TREEMAP — TRAVERSING
16.1 TreeMap Traversing Code
TreeMap is traversed using [Link] (a nested class of Map interface). [Link] has getKey() and getValue()
methods.
import [Link].*;
class TreeMapDemo {
public static void main(String argv[]) {
TreeMap<Integer,String> tm = new TreeMap<Integer,String>();
[Link](1001, "LKO");
[Link](1000, "KNP");
[Link](1002, "GKP");
// Traversing using [Link]
for ([Link] m : [Link]()) {
[Link]([Link]() + " " + [Link]());
}
}
}
Output: 1000 KNP
1001 LKO
1002 GKP (sorted by key in ascending order)
📝 Exam Tip: TreeMap automatically sorts by key in ascending order!
🎯 PYQ: Write a program to demonstrate HashMap and TreeMap operations with all key methods.
17. INTERFACE [Link]<K,V>
17.1 Definition
A map entry is a key-value pair. The [Link]() method returns a collection-view of the map whose
elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this
collection-view.
17.2 Methods
➤ getKey(): returns the key corresponding to this entry
➤ getValue(): returns the value corresponding to this entry
➤ setValue(V value): replaces the value corresponding to this entry with the specified value
➤ equals(Object o): compares the specified object with this entry for equality. Returns true if object is also a
map entry and both entries represent same mapping
➤ hashCode(): returns hash code value for this map entry
➤ comparingByKey(): returns a comparator that compares [Link] in natural order on key
➤ comparingByValue(): returns a comparator that compares [Link] by key using the given comparator
18. HASHTABLE CLASS
18.1 Definition
Java Hashtable class implements a hash table which maps keys to values. It inherits Dictionary class and
implements the Map interface. A hashtable is an array of a list. Each list is known as a bucket. The position of the
bucket is identified by calling the hashCode() method.
18.2 Key Properties
➤ Contains unique elements: no duplicate keys
➤ Synchronized: thread-safe (unlike HashMap)
➤ Default initial capacity: 11, load factor = 0.75
➤ Does NOT allow null: neither null key nor null value
18.3 Hashtable Syntax
public class Hashtable<K,V> extends Dictionary<K,V>
// K = type of keys, V = type of mapped values
18.4 Hashtable vs HashMap
Feature Hashtable HashMap
Synchronized Yes (thread-safe) No (not thread-safe)
Null key/value Not allowed One null key, multiple null values
Speed Slow Fast
Legacy Yes (old class) No (modern)
Inherits from Dictionary class AbstractMap class
19. PROPERTIES CLASS
19.1 Definition
The Properties class extends Hashtable class. Its object contains key-value pairs as strings. It is used to get the
property (value) of a specified key from a properties file. It can also be used to get and set the system
properties.
19.2 Advantage
➤ No recompilation needed: if the properties file is modified, Java source file does NOT need to be
recompiled
19.3 Key Methods
➤ void load(Reader r): loads data from the reader object
➤ void load(InputStream is): loads data from the InputStream object
➤ void loadFromXML(InputStream in): loads all the properties represented by XML document
➤ String getProperty(String key): returns value based on the key
➤ void setProperty(String key, String value): calls the put() method of hashtable
➤ void list(PrintStream out): prints the property list to the specified output stream
➤ Set<String> stringPropertyNames(): returns a set of keys where key and value are strings
➤ void storeToXML(Writer w, String comment, String encoding): writes properties in the writer object for
generating XML document
19.4 Properties Class Demo
// Step 1: Create [Link] file with content:
// user = root
// password = root
// Step 2: Java source file
class PropertiesDemo {
public static void main(String argv[]) throws Exception {
FileReader fr = new FileReader("[Link]");
Properties pp = new Properties();
[Link](fr);
[Link]([Link]("User"));
[Link]([Link]("Password"));
}
}
Output: root
root
20. COLLECTION INTERFACE — ALL METHODS
20.1 Complete Method List
➤ boolean add(E e): inserts an element in this collection
➤ boolean addAll(Collection<? extends E> c): inserts specified collection elements into the invoking
collection
➤ boolean remove(Object element): deletes an element from the collection
➤ boolean removeAll(Collection<?> c): deletes all elements of specified collection from invoking collection
➤ boolean removeIf(Predicate<? super E> filter): deletes all elements satisfying the specified predicate
➤ boolean retainAll(Collection<?> c): deletes all elements of invoking collection EXCEPT the specified
collection
➤ int size(): returns total number of elements in the collection
➤ void clear(): removes total number of elements from the collection
➤ boolean contains(Object element): searches an element
➤ Iterator iterator(): returns an iterator
➤ Object[] toArray(): converts collection into array
➤ boolean isEmpty(): checks if the collection is empty
➤ boolean equals(Object element): matches the two collections
➤ int hashCode(): returns hash code number of the collection
➤ Stream<E> stream(): returns a sequential stream with the collection as its name source
21. COLLECTIONS CLASS IN JAVA
21.1 Summary of Main Collection Classes
Class Interface Key Feature Syntax
Implemented
ArrayList List Dynamic array, fast ArrayList<type> name =
access new ArrayList<type>();
Vector List Synchronized dynamic public class Vector<E>
array extends AbstractList<E>
Stack List (extends Vector) LIFO structure public class Stack<E>
extends Vector<E>
LinkedList List + Deque Doubly linked list LinkedList name = new
LinkedList();
PriorityQueue Queue Heap-based, natural PriorityQueue<E>
ordering extends
AbstractQueue<E>
ArrayDeque Deque Double-ended, fast public class
insert/delete both ends ArrayDeque<E> extends
AbstractCollection<E>
22. IMPORTANT PYQ PROGRAMS — MUST PRACTISE
PYQ 1: ArrayList with User-defined Class
class Student {
int rollno;
String name;
Student(int r, String n) { rollno = r; name = n; }
public String toString() { return rollno + " " + name; }
}
class ArrayListStudent {
public static void main(String args[]) {
ArrayList<Student> al = new ArrayList<Student>();
[Link](new Student(101, "Rahul"));
[Link](new Student(102, "Priya"));
[Link](new Student(103, "Amit"));
for (Student s : al)
[Link](s);
}
}
Output: 101 Rahul
102 Priya
103 Amit
PYQ 2: TreeSet with Comparable (Sorting Student by Marks)
import [Link].*;
class Student implements Comparable<Student> {
Integer marks;
Student(Integer marks) { [Link] = marks; }
public String toString() { return "" + [Link]; }
public int compareTo(Student stu) {
return [Link]([Link]);
}
}
class GPG {
public static void main(String args[]) {
TreeSet<Student> set = new TreeSet<>();
[Link](new Student(500));
[Link](new Student(300));
[Link](new Student(400));
[Link](new Student(100));
[Link](new Student(200));
[Link]("Sorted: " + set);
}
}
Output: Sorted: [100, 200, 300, 400, 500]
PYQ 3: HashMap — All Basic Operations
import [Link].*;
class HashMapPYQ {
public static void main(String args[]) {
HashMap<String, Integer> map = new HashMap<>();
[Link]("Alice", 90);
[Link]("Bob", 75);
[Link]("Charlie", 85);
[Link]("Map: " + map);
[Link]("Alice's marks: " + [Link]("Alice"));
[Link]("Bob");
[Link]("After removing Bob: " + map);
[Link]("Contains Charlie? " + [Link]("Charlie"));
// Traverse using entrySet
for ([Link]<String,Integer> e : [Link]())
[Link]([Link]() + " -> " + [Link]());
}
}
Output: Map: {Alice=90, Bob=75, Charlie=85}
Alice's marks: 90
After removing Bob: {Alice=90, Charlie=85}
Contains Charlie? true
Alice -> 90
Charlie -> 85
PYQ 4: PriorityQueue Demonstration
import [Link].*;
class PQDemo {
public static void main(String args[]) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
[Link](40);
[Link](10);
[Link](30);
[Link](20);
[Link]("Head: " + [Link]());
[Link]("Poll: " + [Link]()); // removes min
[Link]("Remaining: " + pq);
}
}
Output: Head: 10
Poll: 10
Remaining: [20, 40, 30]
PYQ 5: LinkedList as Queue
import [Link].*;
class LinkedListQueue {
public static void main(String args[]) {
LinkedList<String> queue = new LinkedList<>();
[Link]("First");
[Link]("Second");
[Link]("Third");
[Link]("Front: " + [Link]());
[Link]("Removed: " + [Link]());
[Link]("Queue now: " + queue);
}
}
Output: Front: First
Removed: First
Queue now: [Second, Third]
23. QUICK REVISION TABLE — FOR LAST HOUR BEFORE EXAM
Collection Order? Duplicates? Null? Synchronized Underlying DS
?
ArrayList Insertion order Yes Yes No Dynamic Array
LinkedList Insertion order Yes Yes No Doubly Linked
List
Vector Insertion order Yes Yes Yes Dynamic Array
Stack LIFO Yes Yes Yes Extends Vector
HashSet No order No One null No Hash Table
LinkedHashSet Insertion order No One null No Hash Table + LL
TreeSet Sorted (asc) No No null No Red-Black Tree
PriorityQueue Priority order Yes No null No Heap
ArrayDeque Insertion order Yes No null No Resizable Array
HashMap No order No (keys) One null key No Hash Table
LinkedHashMa Insertion order No (keys) One null key No Hash Table + LL
p
TreeMap Sorted by key No (keys) No null key No Red-Black Tree
Hashtable No order No (keys) No null Yes Hash Table
All the best for your exams! 🎓