Java Day 9
Java Day 9
ArrayIndexOutOfBoundsException .
If you want to keep the elements always sorted, despite insertions and
deletions
2. Implementations
It contains a set of classes that provide implementations of the interfaces.
In simple words:
3. Algorithms
The Collection Framework provides a wide range of methods that perform
commonly used operations.
Dynamic Arrays
Linked Lists
Hash Tables
3. Flexibility
2. Map
→ Multiple objects are handled in the form of key-value pairs
boolean
Returns true if this collection contains all the elements in the
containsAll(Collection<?
> c)
specified collection.
boolean equals(Object
Compares the specified object with this collection for equality.
o)
boolean Removes all elements from this collection that are also contained in
removeAll(Collection<?> the specified collection (optional operation). After this call, no
c) elements from the specified collection will remain in this collection.
boolean Retains only the elements in this collection that are also contained
retainAll(Collection<?> in the specified collection (optional operation). Removes everything
c) else.
📘 java.util.List<E> Interface
Overview
The List interface provides an ordered collection — elements are arranged
according to their insertion order.
List is zero-based, meaning the first element has an index of 0, just like
arrays.
Method Description
void add(int index, E Inserts the specified element at the specified position in this list
element) (optional operation).
boolean addAll(int
Inserts all elements from the specified collection into this list at the
index, Collection<?
extends E> c) specified position (optional operation).
E get(int index) Returns the element at the specified position in this list.
int lastIndexOf(Object Returns the index of the last occurrence of the specified element,
o) or -1 if the element is not present.
ListIterator<E> Returns a list iterator over the elements in this list, in proper
listIterator() sequence.
ListIterator<E>
Returns a list iterator, starting at the specified index.
listIterator(int index)
E remove(int index) Removes the element at the specified index (optional operation).
E set(int index, E Replaces the element at the specified index with the given element
element) (optional operation).
List<E> subList(int Returns a view of the portion of this list between fromIndex
fromIndex, int toIndex) (inclusive) and toIndex (exclusive).
ArrayList
LinkedList
Vector
Stack
Let me know if you'd like this as a PDF, formatted note sheet, or need a similar
explanation for Set , Map , or other collection interfaces.
Sometimes it's not possible to know the exact size of an array in advance. To
handle such situations, Java provides the ArrayList class.
🏗️ Constructors of ArrayList
Constructor Description
ArrayList(int
Constructs an empty list with the specified initial capacity.
initialCapacity)
Method Description
void ensureCapacity(int Ensures that the ArrayList has at least the specified minimum
minCapacity) capacity.
import java.util.*;
ls.add("A");
ls.add("B");
ls.add(1, "W"); // Inserts "W" at index 1 → [A, W, B]
ls.add("D");
ls.add("D"); // Duplicate element allowed
ls.add("T");
ls.add(null); // null allowed
ls.add(null); // Multiple nulls allowed
🔁 Traversing an ArrayList
java.util.Queue<T> Interface
Queueis a subinterface of Collection used to hold elements prior to
processing.
In any ordering, the head element is the one to be removed first, and new
elements are inserted at the tail.
boolean add(E Inserts the specified element into this queue if space is available. Throws
e) IllegalStateException if the queue is full.
Retrieves, but does not remove, the head of this queue. Throws an
E element()
exception if the queue is empty.
Retrieves and removes the head of this queue. Throws an exception if the
E remove()
queue is empty.
boolean offer(E Inserts the specified element into this queue if possible. Returns false if
e) space is unavailable.
Retrieves, but does not remove, the head of this queue, or returns null if
E peek()
empty.
E poll() Retrieves and removes the head of this queue, or returns null if empty.
📘 java.util.Deque<T> Interface
🔧Collection
Methods Specific to Deque (in addition to Queue and
methods)
Method Description
void addFirst(E e) Inserts the element at the front. Throws IllegalStateException if full.
void addLast(E e) Inserts the element at the rear. Throws IllegalStateException if full.
Retrieves, but does not remove, the first element. Throws exception
E getFirst()
if empty.
Retrieves, but does not remove, the last element. Throws exception
E getLast()
if empty.
E removeFirst() Retrieves and removes the first element. Throws exception if empty.
E removeLast() Retrieves and removes the last element. Throws exception if empty.
boolean offerFirst(E e) Inserts the element at the front. Returns false if full.
boolean offerLast(E e) Inserts the element at the rear. Returns false if full.
Retrieves, but does not remove, the first element. Returns null if
E peekFirst()
empty.
Retrieves, but does not remove, the last element. Returns null if
E peekLast()
empty.
E pollFirst() Retrieves and removes the first element. Returns null if empty.
E pollLast() Retrieves and removes the last element. Returns null if empty.
📘 java.util.LinkedList<T> Class
A doubly-linked list implementation of both List and Deque interfaces.
🧪 Example:
File: Customer.java
@Override
public String toString() {
return "Customer [customerId=" + customerId + ", customerName=" + c
ustomerName + ", orderAmount=" + orderAmount + "]";
}
}
File: LinkedListDemo.java
sc.close();
}
Output:
Enter customer id, name and order amount C001 Aman 2541
Do you want to add another customer (y/n) y
Enter customer id, name and order amount C002 Bajrag 5858
Do you want to add another customer (y/n) y
Enter customer id, name and order amount C003 Cindrella 14526
Do you want to add another customer (y/n) n
📘 java.util.Vector<T> Class
Vector is one of the implementation classes of List interface.
🔧 Stack Methods
Method Description
E push(E item) Pushes an item onto the top of the stack.
E peek() Returns the item at the top without removing it.
E pop() Removes and returns the item at the top.
🧪 Example:
import java.util.Stack;
stack.push("A");
stack.push("B");
stack.push("C");
stack.push("D");
stack.push("E");
Output:
ABCD
📘 java.util.Set<T> Interface
Overview
Set<T> is a subinterface of Collection .
At most one null element can be added (though some implementations like
TreeSet do not allow null ).
It inherits all methods from the Collection interface but does not define any new
methods.
🔗 Set Hierarchy
java.util.Collection
|
java.util.Set
|
----------------------------
| | |
HashSet LinkedHashSet TreeSet
🔹 Characteristics
No guaranteed iteration order (order may change over time).
🏗️ Constructors of HashSet
Constructor Description
Constructs an empty set with default capacity (16) and load factor
HashSet()
(0.75).
HashSet(int Constructs an empty set with the specified initial capacity and default
initialCapacity) load factor.
HashSet(int
initialCapacity, float Constructs an empty set with the given capacity and load factor.
loadFactor)
🧪 Example
import java.util.HashSet;
import java.util.Set;
System.out.println(hs);
System.out.println(hs.size());
}
}
Output:
[P, Q, B, D, E, W]
6
🔹 Characteristics
LinkedHashSet is a subclass of HashSet , but does not add new methods.
import java.util.LinkedHashSet;
import java.util.Set;
System.out.println(hs);
System.out.println(hs.size());
}
}
Output:
[W, E, Q, D, B, P]
6
📂 java.util.TreeSet<E> Class
▶️ Overview
Implements the Set interface.
Provides guaranteed log(n) time complexity for operations like add , remove ,
and contains .
📊 Constructors of TreeSet
Constructor Description
TreeSet() Constructs an empty set, sorted according to the natural ordering.
TreeSet(Collection<? Constructs a set with elements from the specified collection, sorted
extends E> c) naturally.
TreeSet(SortedSet<E> Constructs a set with the same elements and ordering as the given
s) sorted set.
System.out.println(dateSet);
}
}
[a,b,c]
📌 java.util.Comparator<E> Interface
▶️ Purpose
Used to define custom sorting logic when natural ordering is not desired.
🔧 Methods
Method Description
Output:
📈 java.util.PriorityQueue<E> Class
▶️ Overview
A Queue implementation with priority-based ordering.
📊 Constructors
Constructor Description
PriorityQueue() Default capacity 11; natural ordering.
PriorityQueue(int
Specified capacity; natural ordering.
initialCapacity)
PriorityQueue(Comparator<?
Comparator-based priority queue.
super E>)
PriorityQueue(Collection<?
Based on given collection.
extends E>)
PriorityQueue(PriorityQueue<?
Based on another PQ.
extends E>)
PriorityQueue(SortedSet<?
Based on a sorted set.
extends E>)
Output:
Output:
🔄 Comparable vs Comparator
Feature Comparable Comparator
A Map cannot have duplicate keys, and each key maps to a single value only.
1. A set of keys
2. A set of values
A Map cannot contain itself as a key but can contain itself as a value.
boolean
Returns true if this map maps one or more keys to the specified
containsValue(Object
value)
value.
Set<Map.Entry<K,V>>
Returns a Set view of the mappings contained in this map.
entrySet()
int hashCode() Returns the hash code value for this map.
V get(Object key) Returns the value for the given key or null if not found.
boolean isEmpty() Returns true if this map contains no key-value mappings.
Set<K> keySet() Returns a Set view of the keys.
V put(K key, V value) Associates the specified value with the specified key.
void putAll(Map<?
extends K, ? extends Copies all mappings from the specified map.
V> m)
V remove(Object
Removes the mapping for a key, if present.
key)
Entries retrieved from entrySet() are valid only during that iteration.
Methods of Map.Entry
Method Description
boolean equals(Object o) Compares the specified object with this entry for equality.
K getKey() Returns the key.
V getValue() Returns the value.
int hashCode() Returns the hash code value for this map entry.
V setValue(V value) Replaces the value with the specified value.
Constructors of HashMap
Constructor Description
HashMap() Default initial capacity 16 and load factor 0.75.
HashMap(int
Sets specified capacity, default load factor.
initialCapacity)
HashMap(int initialCapacity,
Sets both capacity and load factor.
float loadFactor)
HashMap(Map<? extends
Initializes with the same mappings as the specified map.
K,? extends V> m)
Example
import java.util.*;
System.out.println(hm);
System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
hm.remove("Well");
hm.put("Well!", 4);
while (itr.hasNext()) {
Map.Entry<String, Integer> entry = itr.next();
System.out.print(entry.getKey() + ":" + entry.getValue() + " ");
}
}
}
Output:
Constructors
Constructor Description
LinkedHashMap(int
initialCapacity, float Constructs a LinkedHashMap with specified capacity, load factor,
loadFactor, boolean and ordering mode.
accessOrder)
Common Methods
Method Description
Comparator<? super K> Returns comparator used to order keys, or null if natural ordering
comparator() is used.
Set<Map.Entry<K,V>>
Returns a set view of the mappings.
entrySet()
SortedMap<K,V> Returns portion of the map with keys greater than or equal to
tailMap(K fromKey) fromKey .
Output:
Constructors
Constructor Description
TreeMap() Constructs empty tree map using natural key ordering.
TreeMap(Comparator<?
Constructs tree map using the given comparator.
super K> comparator)
TreeMap(Map<? extends K, Constructs tree map with same mappings as specified map,
? extends V> m) using natural ordering.
TreeMap(SortedMap<K, ? Constructs tree map with mappings and ordering of the specified
extends V> m) sorted map.
StudentMarksComp.java
import java.util.Comparator;
TreeMapDemo.java
import java.util.*;
for(Map.Entry<Student,String> me : tm.entrySet()) {
System.out.println("Toppers Student of State " + me.getValue() + " is "
+ me.getKey());
Output:
Toppers Student of State Tamilnadu is Roll No: 12 Name: Surya Marks: 850
Toppers Student of State Kerla is Roll No: 18 Name: Srinu Marks: 880
Toppers Student of State Haryana is Roll No: 16 Name: Dinesh Marks: 910
Toppers Student of State Telangana is Roll No: 15 Name: Venkat Marks: 920
Toppers Student of State Maharastra is Roll No: 10 Name: Ganesh Marks: 950