COLLECTIONS
This page explains Wrapper Classes in Java, which are used to convert:
Primitive data types (like int, float) into objects
And back from objects to primitive types
Java provides 8 wrapper classes in the java.lang package:
Primitive Type Wrapper Class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Why use them?
Collections (like ArrayList) work with objects, not primitives.
Wrapper classes help use primitive values in such cases.
Example methods:
intValue(): Converts an object (like Integer) to primitive int.
doubleValue(): Converts a Double object to primitive double.
In short: Wrapper classes help handle primitive values as objects when needed in Java.
Here is a brief and simple explanation of the content shown in the image:
Collections Framework in Java (java.util)
What is a Collection?
A Collection is a group of objects (like a list of items).
What is a Framework?
A Framework gives you a ready structure to work with.
It includes classes and interfaces (code blueprints).
Using it is optional, but helpful.
What is the Collections Framework?
It is a set of tools in Java to store and manage groups of data.
It includes:
1. Interfaces and their classes (like List, Set, Map)
2. Algorithms (for sorting, searching, etc.)
Hierarchy of Collections
Main Interfaces:
List (e.g., ArrayList, LinkedList, Vector, Stack)
Queue (e.g., PriorityQueue, ArrayDeque)
Set (e.g., HashSet, LinkedHashSet, TreeSet)
Map (e.g., HashMap, LinkedHashMap, TreeMap, Hashtable)
Key Interfaces and Classes
Iterable: Root interface. Allows looping using iterator().
Collection: Base for all collection types like List, Set, Queue.
List
Ordered collection. Can have duplicates.
Examples: ArrayList, LinkedList, Vector, Stack
Queue
Follows First-In-First-Out.
Examples: PriorityQueue, ArrayDeque
Set
No duplicate elements allowed.
Examples: HashSet, LinkedHashSet, TreeSet
Map
Stores key-value pairs.
Keys are unique.
Types:
HashMap, LinkedHashMap: allow one null key, many null value.
TreeMap: sorted, no null keys
Example of Creating Collections
List<String> list1 = new ArrayList<>();
Queue<String> q1 = new PriorityQueue<>();
Set<Integer> s1 = new HashSet<>();
Map<Integer, String> map = new HashMap<>();
This is a core part of Java programming used to manage groups of objects easily and
efficiently.
This image explains some important methods of the Collection interface in Java. Here's a
brief and simple explanation:
🔹 Common Collection Methods:
1. add(Object) – Adds one element to the collection.
2. addAll(Collection) – Adds all elements from another collection.
3. remove(Object) – Removes one element from the collection.
4. removeAll(Collection) – Removes all matching elements from another collection.
5. retainAll(Collection) – Keeps only the common elements (removes others).
6. size() – Returns the number of elements in the collection.
7. clear() – Removes all elements from the collection.
8. contains(Object) – Checks if an element exists.
9. containsAll(Collection) – Checks if all elements of another collection exist.
10. iterator() – Returns an iterator to loop through elements.
11. toArray() – Converts collection into an array.
12. isEmpty() – Checks if the collection is empty.
13. equals(Object) – Compares two collections.
14. hashCode() – Returns a hash code value (used in hashing).
🔸 Some Common Collection Classes:
ArrayList, LinkedList, HashSet, TreeSet, PriorityQueue, ArrayDeque
These methods help manage and manipulate groups of objects in Java easily.
This image explains the ArrayList and LinkedList classes in Java:
🔹 ArrayList
Uses a dynamic array to store elements (can grow or shrink).
Like an array but has no size limit.
Faster for reading but slower when inserting/removing in the middle (needs shifting).
Allows duplicates and maintains order of insertion.
Found in java.util package.
Needs wrapper classes (e.g., Integer, Float) for primitive types.
Example Code:
ArrayList<String> a = new ArrayList<>();
a.add("india");
a.add("america");
a.add("russia");
a.add("germany");
System.out.println(a);
Output: [india, america, russia, germany]
🔹 LinkedList
Uses a doubly linked list.
Better for fast insertions/removals (no shifting needed).
Also allows duplicates and keeps order.
Can act as a list, stack, or queue.
Also part of java.util and implements List and Deque interfaces.
📌 Key Difference:
ArrayList = better for accessing elements.
LinkedList = better for adding/removing elements.
HashSet (Java) – Simple Explanation:
HashSet is a collection in Java that stores unique elements only (no duplicates).
It uses hashing to store items efficiently.
It inherits from AbstractSet and implements the Set interface.
It doesn't maintain order of elements (insertion order is not preserved).
It allows one null value.
It's great for fast searching.
Default size (capacity) is 16, and load factor is 0.75.
Load factor means: when 75% is full, the size increases.
Example: Capacity = 20 → resize happens after adding 15 items.
List vs Set:
List → allows duplicates
Set → only unique elements
In short: HashSet is best when you need fast lookup and no duplicates.
Here's a simple and brief explanation of the content:
TreeSet in Java
TreeSet is a class that stores unique elements in ascending order.
It implements the Set interface and uses a tree structure internally.
No duplicates and no null values allowed.
Fast for access and retrieval.
Automatically sorts elements.
Example:
Adding numbers: [12, 15, 24, 66] → TreeSet stores them sorted.
Methods like:
pollFirst() → gets the smallest value.
pollLast() → gets the largest value.
Works with strings too, with methods like:
descendingSet() → reverse order.
headSet(), tailSet(), subSet() → for partial views.
Java Queue Interface
Queue is used to store elements in FIFO (First In First Out) order.
Elements are added at the end and removed from the front.
Found in java.util package.
Common Implementations:
PriorityQueue, ArrayBlockingQueue, and LinkedList.
Notes:
Adding null to a queue can cause a NullPointerException.
PriorityQueue lets you process elements by priority, not just FIFO.
Use poll() to remove the first element in the queue.
Let me know if you want the example code explained too.
Java Deque Interface – Simple Explanation:
Deque (in java.util) is a type of Queue.
It stands for "double ended queue", meaning:
You can add or remove elements from both ends (front and rear).
So, it can act like a Stack (LIFO) or a Queue (FIFO).
Key Points:
Used as stack or queue.
Grows and shrinks with usage.
Nulls are not allowed in ArrayDeque.
ArrayDeque:
Has no size limit.
Is faster than LinkedList and Stack.
In short: Deque is a flexible and efficient data structure for both stack and queue operations.
This explains four ways to access elements in a Java Collection using different looping
methods:
✅ 1. For-each Loop
Used for object-based retrieval (not index-based).
Automatically goes through each element in a collection.
Example:
for (type var : collection) {
// use var
✅ 2. Iterator Interface
Used to loop through elements one-by-one.
Has 3 methods:
1. hasNext() – checks if more elements exist.
2. next() – returns the next element.
3. remove() – deletes the last returned element.
✅ 3. ListIterator Interface
Can iterate in both directions (forward and backward).
Methods:
1. hasNext() – checks for next element.
2. hasPrevious() – checks for previous element.
3. next() – gets next element.
4. previous() – gets previous element
5. remove() – removes the last element returned.
🆚 Difference from Iterator:
Iterator only moves forward, ListIterator moves forward and backward.
✅ 4. Enumeration Interface
An old way to access elements one by one.
Has 2 methods:
1. hasMoreElements() – checks if elements remain.
2. nextElement() – returns the next element.
Summary:
Method Direction Can Remove Elements Modern Use?
For-each loop Forward only No Yes
Iterator Forward only Yes Yes
ListIterator Both ways Yes Yes
Enumeration Forward only No No (outdated)
This image explains Java HashMap and LinkedHashMap classes, which are part of the Map
interface.
🔹 Java HashMap:
Stores key-value pairs.
Keys are unique.
One null key allowed, many null values allowed.
No order is maintained.
Example program:
Adds three key-value pairs to a HashMap.
Prints each entry.
Output:
100 Amit
101 Vijay
102 Rahul
🔹 Java LinkedHashMap:
Similar to HashMap.
Also stores key-value pairs with unique keys, allows one null key and multiple null values.
Maintains insertion order (unlike HashMap).
In short:
Use HashMap when order doesn't matter.
Use LinkedHashMap when you want to keep the order in which items were added.
Java TreeMap Class – Simple Explanation
TreeMap Overview:
Stores key-value pairs in ascending key order.
Keys must be unique.
Null keys not allowed, but null values are allowed.
Works like HashMap but keeps entries sorted by key.
Example Program:
TreeMap<Integer, String> hm = new TreeMap<>();
hm.put(100, "Amit");
hm.put(102, "Ravi");
hm.put(101, "Vijay");
hm.put(103, "Rahul");
for (Map.Entry m : hm.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
Output:
100 Amit
101 Vijay
102 Ravi
103 Rahul
✅ The keys are printed in ascending order, automatically sorted by TreeMap.
For-each Loop (Enhanced for Loop):
Purpose
Used to loop through collections like arrays, lists, maps without using indexes.
Syntax:
for (type variable : collection) {
// statements
Key Points:
Object-based retrieval (not index-based).
Loops through each item automatically.
Runs once for every element in the collection.
Example:
for (String name : names) {
System.out.println(name);
This is easier and cleaner than using a traditional for loop when you don't need an index
This explains the Arrays class in Java, which is part of the java.util package. It provides helpful
static methods to work with arrays—like sorting, searching, comparing, and converting.
Key Methods:
1. binarySearch() – Finds an element in a sorted array using binary search.
2. asList() – Converts an array into a List.
3. sort(array) – Sorts the whole array in ascending order.
4. equals(array1, array2) – Checks if two arrays are equal (same size and elements in the same
order).
These methods make array handling in Java easier and faster.
Here’s a simple and brief explanation of the image:
Hashtable
A Hashtable stores key-value pairs.
It uses buckets to store data, placed based on a key’s hash code.
Only unique keys are allowed.
Null keys or values are not allowed.
It is synchronized (thread-safe).
Vector
A Vector is a dynamic array (can grow or shrink).
It stores any type of data (int, float, objects, etc.).
Found in *java.util* package.
It is a child of AbstractList and supports all List methods.
It starts with a fixed capacity, but this can grow or shrink as needed.
Enumeration Interface
Used to retrieve elements one by one (like an Iterator).
Has two main methods:
1. hasMoreElements() – checks if more elements are available.
2. nextElement() – returns the next element.
In short:
Hashtable = Key-value store, no nulls, thread-safe
Vector = Resizable array
Enumeration = Simple way to go through elements one at a time
Stack in Java – Simple Explanation
A Stack is a data structure that follows LIFO (Last-In-First-Out).
It means the last item added is the first one to be removed.
Key Features:
Insertion/Deletion happens at the top.
It uses Java’s collection framework.
Common methods:
push() → adds item
pop() → removes top item
peek() → views top item
search() → finds position of an item
empty() → checks if the stack is empty
size() → returns number of items
Java Code Example:
Stack s = new Stack(); // Create a stack
s.push("abc"); // Add items
s.push("xyz");
s.push("pqr");
s.push("hhh");
s.push(10);
s.push('x');
Then we:
Print the stack
View the top using peek()
Remove the top using pop()
Check if empty
Search for "pqr"
Count size
Output:
[abc, xyz, pqr, hhh, 10, x] // full stack
x // top item
x // removed item
[abc, xyz, pqr, hhh, 10] // after pop
false // not empty
3 // "pqr" is 3rd from top
5 // total 5 elements now
Autoboxing:
Java automatically converts between primitive types and their wrapper classes:
Example: int ↔ Integer
Boxing = int → Integer
Unboxing = Integer → int
Here's a simple explanation of the content in the image:
1. Scanner Class
Purpose: Used to take user input.
Package: java.util
Example:
Scanner s = new Scanner(System.in);
String name = s.nextLine();
It reads a full line from the user.
Example Output:
Enter your name abc
you entered abc
2. StringTokenizer Class
Purpose: Breaks a string into smaller parts (tokens).
Simpler than StreamTokenizer.
Common Methods:
Method Description
hasMoreTokens() Checks if more tokens are available
nextToken() Gets the next token
nextToken(String delim) Gets next token using a specific delimiter
hasMoreElements() Same as hasMoreTokens()
nextElement() Same as nextToken() but returns Object
countTokens() Returns total number of tokens
Example:
StringTokenizer st = new StringTokenizer("this is java lab", " ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
Output:
this
is
java
lab
3. Dictionary Class
Abstract class in java.util package.
Used to map keys to values.
Hashtable is a direct subclass.
Both keys and values must be non-null objects.
Let me know if you want examples or comparison between these.