0% found this document useful (0 votes)
12 views70 pages

Unit 4 (JP)

Uploaded by

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

Unit 4 (JP)

Uploaded by

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

The Collection

Framework in Java
UNIT-IV
java.util package
• The important package that contains large number of classes and
interfaces that support broad range of functionality.
• Examples: tokenize string, date and time etc.
• The java.util package also contains one of the most powerful
subsystems: Collections Framework.
• It is a sophisticated hierarchy of interfaces and classes that provide
state-of-the-art technology for managing groups of objects.
Java Collection Framework-
background
Collections
• The Collection in Java is a frame work that provides an architecture to
store and manipulate the group of objects.
• The Java Collections Framework standardizes the way in which
groups of objects are handled by your programs.
• Collections were not part of the original Java release, but Prior to the
Collections Framework , Java provided ad-hoc classes such as to store
and manipulate groups of objects. Dictionary, Vector, Stack, and
Properties.
• When the Collections framework were added in J2SE1.2, the original
classes were reengineered to support the collection interface. These
classes are also known as Legacy classes. All legacy classes and
interface were redesign by JDK5 to support Generics.
The following are the legacy classes defined by java.util package.
• Dictionary
• HashTable
• Properties
• Stack
• Vector
• There is only one legacy interface called Enumeration.
NOTE: All the legacy classes are synchronized
Java collection Framework
Collection Interfaces
interface Collection<E>
Here E represents the type of Objects that the Collection will hold.
Here are the main collection interfaces in Java's java.util package:
Collection – Root interface for all collections.
List – Ordered collection allowing duplicates (e.g., ArrayList, LinkedList).
Set – Unordered collection without duplicates (e.g., HashSet).
SortedSet – Set with elements in natural order (e.g., TreeSet).
Queue – Holds elements before processing (e.g., PriorityQueue).
Deque – Double-ended queue supporting element insertion at both ends.
List Interface
• List interface extends the Collection interface and declares the behaviour
of a collection that stores sequence of elements.
interface List<E>
Here E represents the type of Objects that the List will hold.
• In addition to methods defined by Collection, List define some methods
of its own.

• Several methods of these will throw an


UnSupportedOperationException (if collection cannot be modified),
ClassCastException (when objects are incompatible) and
IndexOutOfBoundsException (invalid index is used)
Set interface
• The Set interface defines a set. It extents Collection interface, and
decalares the behaviour of a collection that does not allow duplicate
elements. Therefore, add() method returns false if an attempt is made
to add duplicate element to set.
• It does not define any additional methods of its own.

interface Set<E>
Here E represents the type of Objects that the set will hold.
SortedSet interface
• It extends Set interface and declares the behaviour of a set sorted in ascending
order.
interface SortedSet<E>
In SortedSet , several ,methods throw NoSuchElementEXception,
ClassCastException, NullPointerException.
Queue Interface
• The Queue interface was added by J2SE 5. it extends Collection and
declares the behaviour of a queue, which is aften a First-in, First-out
list.
interface Queue<E>
Map Interface
• In Java, Map Interface is present in java.util package
represents a mapping between a key and a value.
• Java Map interface is not a subtype of the
Collection interface.
• Therefore it behaves a bit differently from the rest of the
collection types.
• A map contains unique keys.
• Maps are perfect to use for key-value association mapping
such as dictionaries.
• The maps are used to perform lookups by keys or when
someone wants to retrieve and update elements by keys.
Map Interface
Collection Classes
• ArrayList
• LinkedList
• HashSet
• TreeSet
• PriorityQueue
• HashMap
• TreeMap
ArrayList class
Implements List interface which intern extended from Collection interface.

class ArrayList<E>
Example object creation:
ArrayList<Integer> ai=new ArrayList<Integer>();

Constructors:
ArrayList()
ArrayList(Collection c>
ArrayList(int Capacity)
Operations on ArrayList
1. Adding Elements- add(Object),
2. Changing Elements- set(int index, Object)
3. Removing Elements- remove(Object), remove(int index)
4. Iterating the ArrayList – for loop
5. Get Elements- get(int index)
6. Add Elements Between Two Numbers- add(int index,
Object)
7. ArrayList Sort - Collections.sort(ArrayListObject)
8. Size of Elements – size()
LinkedList

• The LinkedList class is part of the Java Collections Framework and is


available in the java.util package.
• It is a doubly linked list implementation of the List and Deque
interfaces, allowing for efficient insertion and deletion.
Features of LinkedList:

1.Implements List and Deque:


•Can be used as both List (sequential access) and Deque (double-ended queue).
•It supports FIFO (First In, First Out) if used as a queue and LIFO (Last In, First Out) if
used as a stack.
2.Dynamic Size:
•The size of the LinkedList can grow or shrink dynamically as elements are added or
removed.
3.Efficient Insertion/Deletion:
•Inserting or deleting elements is faster compared to ArrayList because it does not
require shifting elements.
4.Allows Nulls:
•The LinkedList can contain null elements.
LinkedList<String> list = new LinkedList<>();

Constructors:
LinkedList()
LinkedList(Collection c)

Additional methos:
Void addFirst(E object)
Void addLast(E object)
E getFirst()
E getLast()
E removeFirst()
E removeLast()
Common Methods of LinkedList:
• list.add("Apple"); // Add element at the end
• list.addFirst("Mango"); // Add element at the start
• list.addLast("Banana"); // Add element at the end

• System.out.println(list); // [Mango, Apple, Banana]

• list.remove("Apple"); // Remove specific element


• list.removeFirst(); // Remove the first element
• list.removeLast(); // Remove the last element
Accessing
• list.add("Orange");
• list.add("Pineapple");

• System.out.println(list.get(1)); // Get element at index 1: "Pineapple"


• System.out.println(list.getFirst()); // Get first element: "Orange"
• System.out.println(list.getLast()); // Get last element: "Pineapple"
Iterating
for (String fruit : list) {
System.out.println(fruit);
}
Checking Size and Clearing List
• System.out.println("Size: " + list.size()); // Size of the list

• list.clear(); // Remove all elements


• System.out.println(list.isEmpty()); // Check if the list is empty
Queue and Deque Operations:
• Queue Operations (FIFO):
• list.add("Apple");
• list.add("Mango");

• System.out.println(list.poll()); // Retrieves and removes the first


element: "Apple"
• System.out.println(list.peek()); // Retrieves but does not remove:
"Mango"
• Stack Operations (LIFO)
• list.push("Banana"); // Push element to the front
• System.out.println(list.pop()); // Removes and returns the first
element
LinkedList vs ArrayList
HashSet
• The HashSet class is part of the Java Collections Framework and is
found in the java.util package.
• It implements the Set interface, which means it stores unique
elements only, with no duplicate values allowed.
• Internally, it uses a hash table to store the elements, which makes
operations like add, remove, and search very fast.

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


Constructors:
HashSet()
HashSet(Collection c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
Features of HashSet:
1.No Duplicates:
•HashSet does not allow duplicate elements. If you try to add a duplicate,
the insertion is ignored.
2.Unordered:
•The elements are not stored in any particular order (like insertion or
sorted order).
3. Allows Null Value:
•A HashSet can contain a single null element.
4. Non-Synchronized:
•HashSet is not thread-safe, meaning multiple threads should not modify
it without synchronization.
Adding elements
hset.add("Apple");
hset.add("Mango");
hset.add("Banana");
hset.add("Apple"); // Duplicate, will be ignored

System.out.println(hset); // Output: [Banana, Mango, Apple] (Order


not guaranteed)
Removing elements
hset.remove("Mango"); // Removes "Mango" from the set
System.out.println(hset); // Output: [Banana, Apple]
Checking for an Element:
• System.out.println(hset.contains("Apple")); // Output: true
Iterating through a HashSet:

for (String fruit : set) {


System.out.println(fruit);
}

Iterator<String> iterator = set.iterator();


while (iterator.hasNext()) {
System.out.println(iterator.next());
}
TreeSet class
• The TreeSet class in Java is part of the Java Collections Framework and
is available in the java.util package.
• It implements the SortedSet interface, meaning it stores sorted
unique elements only.
• Internally, it is backed by a balanced tree (Red-Black Tree), which
keeps the elements sorted in natural or custom order.

TreeSet<Integer> treeSet = new TreeSet<>();


Constructors
TreeSet()
TreeSet(Collection c)
TreeSet(Comparator comp)
TreeSet(SortedSet s)
Key Features of TreeSet:
1.Sorted Elements:
•Maintains elements in ascending order by default (natural ordering).
•You can provide a custom comparator for custom sorting.
2.Unique Elements:
•Does not allow duplicate elements.
3.No Null Elements (since Java 7):
•Adding null will throw a NullPointerException if the TreeSet has any
other elements.
4. Not Synchronized:
•TreeSet is not thread-safe, meaning external synchronization is
needed for multi-threaded environments.
Adding elements
treeSet.add(10);
treeSet.add(5);
treeSet.add(20);
treeSet.add(15);

System.out.println(treeSet); // Output: [5, 10, 15, 20] (Sorted order)


Removing elements
treeSet.remove(10); // Remove element 10
System.out.println(treeSet); // Output: [5, 15, 20]

Iterating

for (Integer number : treeSet) {


System.out.println(number);
}
Retrieving elements
System.out.println(treeSet.first()); // Output: 5 (First element)
System.out.println(treeSet.last()); // Output: 20 (Last element)

Checking for an Element:


System.out.println(treeSet.contains(15)); // Output: true

Finding Subsets and Ranges:


TreeSet<Integer> subSet = (TreeSet<Integer>) treeSet.subSet(5, 20);
System.out.println(subSet); // Output: [5, 15]
Checking Size and Clearing:
System.out.println("Size: " + treeSet.size()); // Output: 3

treeSet.clear(); // Remove all elements


System.out.println(treeSet.isEmpty()); // Output: true
TreeSet vs HashSet vs ArrayList:
PriorityQueue
• PriorityQueue implements Queue interface extends AbstractQueue
• Created a queue that is prioritized based on queue’s comparator.
• Priority queues are based on priority: as items are inserted,
whatever is currently the most important will be retrieved first.
Constructors:
PriorityQueue()
PriorityQueue(int capacity)
PriorityQueue(int capacity, Comparator comp)
PriorityQueue(Collection c)
PriorityQueue(PriorityQueue q)
PriorityQueue(SortedSet c)
HashMap class
• The HashMap class in Java is part of the java.util package and is
widely used for storing key-value pairs.
• It implements the Map interface, which allows you to store and
retrieve data based on unique keys.

HashMap<K, V> map = new HashMap<>();


Features of HashMap:
1.Key-Value Mapping: Each key maps to a specific value. Keys
are unique, but multiple keys can have the same value.
2.No Ordering: The elements in a HashMap are not stored in any
particular order (like insertion order or sorted order).
3.Allows Null Values: HashMap allows one null key and multiple
null values.
4.Not Synchronized: It is not thread-safe. If multiple threads
access a HashMap concurrently, synchronization must be handled
externally.
Internal Structure of HashMap:
• Internally, HashMap uses an array of buckets (a linked list or tree
nodes) to store data.
• The hash function maps keys to buckets by calculating their hash
code. If multiple keys map to the same bucket, collision occurs.
• Hash Collision: When collisions happen, they are resolved using a
linked list or binary tree (when many keys map to the same bucket).
Constructors of HashMap:
• HashMap()
• HashMap(int initialCapacity)
• HashMap(int initialCapacity, float loadFactor)
• a load factor of 0.75 means the HashMap will increase its capacity when 75%
of the buckets are filled.
• HashMap(Map<K, V> m)
Important Methods of HashMap:
• put(K key, V value)
• get(Object key)
• remove(Object key)
• containsKey(Object key)
• containsValue(Object value)
• size()
• isEmpty()
• keySet()
• values()
• entrySet()
How HashMap
1.Hashing: Works
When you call the put() Internally:
method, the key's hash code is computed

using hashCode(). This hash code is used to determine the bucket index in the

internal array.

2.Collision Resolution: If two keys map to the same bucket, a linked list or

binary tree is used. After Java 8, if the size of the linked list exceeds a

threshold, the list is converted to a binary search tree to improve

performance.

3.Rehashing: When the number of key-value pairs exceeds the load factor

threshold, the capacity of the internal array is doubled, and the existing

elements are rehashed.


TreeMap class
• The TreeMap class in Java, part of the java.util package, implements
the SortedMap interface.
• It is a map-based collection that stores key-value pairs in a sorted,
ordered manner based on the natural ordering of its keys (or by a
custom comparator).
Features of TreeMap:
1.Sorted Order:
The keys are stored in a sorted ascending order (either natural ordering
or by a custom comparator).
2.Self-Balancing Tree:
Internally, TreeMap is implemented as a Red-Black Tree, which ensures that
the tree remains balanced for optimal performance.
3.Unique Keys:
Each key in the map must be unique.
4.Thread Safety:
TreeMap is not synchronized, meaning it is not thread-safe. For concurrent
access, you need to wrap it using Collections.synchronizedMap() or use
ConcurrentSkipListMap.
5.Null Handling:
TreeMap does not allow null keys (unlike HashMap), but it allows multiple
Constructors of TreeMap
• TreeMap()
• TreeMap(Comparator com)
• TreeMap(Map<K,V> m)
• TreeMap(SortedMap<K, V> m)
Common Methods of TreeMap:
• put(K key, V value)
• get(Object key)
• remove(Object key)
• containsKey(Object key)
• containsValue(Object value)
• size()
• isEmpty()
• firstKey()
• lastKey()
• subMap(K fromKey, K toKey)
• headMap(K toKey)
• tailMap(K fromKey)
• entrySet()
TASK
• Write about the Legacy classes (Vector, Stack, HashTable, Dictionary,
Properties) in your note book.
• Write the purpose, features, constructors, methods of these each
class.
Iteration over Collections – Iterator and
List Iterator, Enumeration  Cursers
Iterator Interface:
The Iterator interface, is part of the java.util package, allows traversal of a
collection element by element. It works with all types of collections implementing
the Collection interface, such as List, Set, and Queue.
Features of Iterator:
1.Unidirectional Traversal: It only moves forward through the collection.
2.Remove Element Capability: You can remove elements from the underlying
collection during iteration using the remove() method.
3.Fail-Fast: If the collection is structurally modified after creating the iterator
(other than using remove()), it throws a ConcurrentModificationException.
Common Methods of Iterator:
•hasNext(): Returns true if there are more elements in the collection.
•next(): Returns the next element in the collection.
•remove(): Removes the last element returned by the next() method.
Usage:

Iterator<String> iterator = alist.iterator();


Here alist is the object of ArrayList

Internally, the iterator() method returns an instance of an inner class (inside ArrayList),
which implements the Iterator interface. This inner class contains the logic to iterate
over the elements of the List.
ListIterator Interface
The ListIterator interface is a specialized version of the Iterator that is only

available for lists, such as ArrayList or LinkedList. It provides more

functionality than the Iterator, such as bidirectional traversal, element

modification, and index-based access.

Features of ListIterator:

1.Bidirectional Traversal: It allows moving both forward and backward

through the list.

2.Add/Modify Elements: You can add new elements or replace existing

elements during iteration.

3.Works with Lists Only: Unlike Iterator, ListIterator works only with List
Common Methods of ListIterator:

•hasNext(): Returns true if there are more elements when moving forward.
•next(): Returns the next element in the list.
•hasPrevious(): Returns true if there are more elements when moving backward.
•previous(): Returns the previous element in the list.
•add(E e): Adds the specified element to the list at the current position.
•set(E e): Replaces the last element returned by next() or previous() with the specified
element.
•remove(): Removes the last element returned by next() or previous().
Enumeration interfaces
• In Java, the Enumeration interface is a legacy interface from the
java.util package.
• It provides methods to iterate over elements in a collection (like
Vector or Hashtable) in a forward-only direction.
• Although it is somewhat similar to the Iterator interface, Enumeration
is considered obsolete for most use cases and is typically replaced by
Iterator or ListIterator in modern Java.
• All legacy classes have implemented the interface Enumeration.
Features of Enumeration Interface:
1.Legacy Interface: Used to iterate over elements of older collections like

Vector, Stack, or Hashtable.

2.Forward-Only Traversal: It can only move forward through elements,

similar to Iterator.

3.Read-Only Access: It does not allow modification of the underlying

collection (no element removal or addition).

4.No Fail-Fast Mechanism: Unlike Iterator, Enumeration does not throw a

ConcurrentModificationException if the collection is modified while iterating.


Methods of Enumeration Interface
• hasMoreElements()
• nextElement()

Usage:
Enumeration<String> enumeration = vector.elements();

Internally, the elements() method returns an instance of an inner class


(inside Vector), which implements the Enumeration interface. This
inner class contains the logic to iterate over the elements of the Vector.
Comparable Interface

 Purpose: Used to define the natural order of objects, i.e., how instances of a class
should be compared to each other.
 Package: java.lang.Comparable
 Method:
o int compareTo(T o);
 Returns:
 0 if both objects are equal
 Negative integer if the current object is "less than" the object passed
 Positive integer if the current object is "greater than" the object passed
Comparator Interface
 Purpose: Used to define custom or multiple sorting criteria that may vary depending on
the situation.
 Package: java.util.Comparator

 Method:
o int compare(T o1, T o2);
 Returns:
 0 if both objects are equal
 Negative integer if the first object is "less than" the second object
 Positive integer if the first object is "greater than" the second object
Java Generics
• Java Generics is a feature that allows you to write code that can work with
different types safely.
• In simple terms, it means that you can create classes, interfaces, and methods that
can operate on any type (like Integer, String, or Double), without sacrificing type
safety. No need for type casting when retrieving elements.
WITHOUT GENERICS:
ArrayList list = new ArrayList();
list.add("Hello");
list.add(123); // NO COMPILATION ERROR
GENERICS:
ArrayList<String> list = new ArrayList<>(); // List holds only Strings
list.add("Hello");
list.add(123); // COMPILATION ERROR
JAVA 8 Features
1. Lambda Expressions
A lambda expression is a concise way to represent an anonymous
function (a function without a name). It allows us to write more
readable and functional code.
Runnable r = () -> System.out.println("Hello from a Lambda!");
new Thread(r).start();
2. Functional Interfaces :A functional interface is an interface with only
one abstract method. Java 8 provides some built-in functional
interfaces like Predicate, Consumer, and Function.
3. Streams API
The Streams API is used to process sequences of data in a functional
style. It allows us to perform operations like filtering, mapping, and
reducing efficiently.
4. Optional Class
The Optional class is used to avoid null checks and prevent
NullPointerException.
5. Default and Static Methods in Interfaces
Java 8 allows default and static methods in interfaces. This provides
backward compatibility without breaking existing code.
6. Method References
Method references provide a shorthand for lambda expressions when a
method is already defined.
7. New Date and Time API
Java 8 introduced the java.time package, which provides better date and time
handling than java.util.Date.
8. Collectors API
The Collectors utility class helps accumulate elements from a stream into
collections, such as lists or maps.
9. Parallel Streams
Java 8 allows the use of parallel streams to leverage multi-core processors for
better performance.
10. Base64 Encoding and Decoding
Java 8 provides built-in Base64 encoding and decoding support.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy