4 Unit4 Part1
4 Unit4 Part1
4 Unit4 Part1
Java(BCS-403)
Unit-4
Prepared By Sandhya Avasthi
[email protected]
Assistant Professor
Department of Computer Science & Engineering
Table of Content
• Collection in Java, Collection Framework in Java
• Hierarchy of Collection Framework
• Iterator Interface
• Collection Interface
• List Interface
• ArrayList
• LinkedList
• Vector
• Stack
• Queue Interface
• Set Interface, Hash set, LinkedHashSet, TreeSet
What is Collection in Java?
• A Collection represents a single unit of objects, i.e., a group.
• In Java, a Collection is a root interface in the Java Collections Framework
(JCF).
• It represents a group of objects (known as elements) in a single unit
including Interfaces and its implementations, i.e., classes and Algorithm
• It is part of the java.util package and serves as the foundation for
various data structures and algorithms that operate on collections of
objects.
Type of Collections
Four main types of collections are:-
1. Queues allow the programmer to insert items in a certain order and
retrieve those items in the same order. An example is a waiting list.
The base interfaces for queues are called Queue.
2. Dictionaries/Maps store references to objects with a lookup key to
access the object's values. One example of a key is an identification
card. The base interface for dictionaries/maps is called Map.
3. Lists are finite collections where it can store the same value multiple
times
4. Sets are unordered collections that can be iterated and contain each
element at most once. The base interface for sets is called set.
Hierarchy of
Collection
Framework
• The java.util package
contains all
the classes and interfaces fo
r the Collection framework.
Hierarchy of Collection Framework
• it illustrates the relationships between different collection types and
their implementations.
• At the top is Iterable interface, which provides a way to iterate over
elements in a collection.
• It is the root interface for all collection types.
• Moving down, Collection interface is a child of Iterable and
represents a group of objects. It defines the common methods and
behaviors for all collection types.
Hierarchy of Collection Framework
There are three main interfaces in collection interface:
• List: An ordered collection that allows duplicate elements. Its
implementations are ArrayList, LinkedList, Vector, and Stack.
• Queue: A collection designed for holding elements prior to
processing. Its implementations are PriorityQueue, Deque, and
ArrayDeque.
• Set: An unordered collection that does not allow duplicate elements.
Its implementations are HashSet, LinkedHashSet, SortedSet, and
TreeSet.
Why collection framework?
• The Java collections framework provides various data structures and algorithms that
can be used directly.
• You do not have to write code to implement these data structures and algorithms
manually.
• Your code will be much more efficient as the collections framework is highly
optimized.
• the collections framework allows us to use a specific data structure for a particular
type of data.
• If we want our data to be unique, then we can use the set.
• To store data in key/value pairs, we can use the Map
• To have resizable array ,use ArrayList
Iterable Interface
• is the root interface for all the collection classes.
• The Collection interface extends the Iterable interface and therefore all
the subclasses of Collection interface also implement the Iterable
interface.
• It contains only one abstract method.
Collection Interface in Java
• The interface which is implemented by all the classes in the collection
framework. It declares the methods that every collection will have
• one of the root interfaces of the Collection Hierarchy
• It is not directly implemented by any class, but it is implemented
indirectly via its subtypes or sub-interfaces like List, Queue, and Set.
Key Features
• It is a part of java.util package .
• It implements the Iterable interface.
• sub-interfaces of Collection are List<E>, Set<E>, Queue<E>, and
others.
Collection interface and Various Methods(1)
SN Method Description/Use
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the
runtime type of the returned array is that of
the specified array.
14 public boolean isEmpty() It checks if collection is empty.
Output ???
Java program
to show
union and
intersection
LinkedHash Set
Insertion Order- Unlike HashSet, LinkedHashSet maintains the insertion order
of elements. When iterating over the set, the elements are returned in the
order they were inserted.
Hash Table Implementation-Like HashSet, LinkedHashSet is also backed by a
hash table data structure (an instance of HashMap) for storing the elements.
This provides constant-time performance for basic operations like add(),
remove(), and contains().
Linked List Implementation- it maintains a doubly-linked list that keeps track
of insertion order of elements.
No Duplicates-it does not allow duplicate elements. When you try to add a
duplicate element, it is ignored.
Null Elements- it allows at most one null element. If you try to add a second
null element, it will be ignored.
LinkedHashSet Example
Sorted Set Interface
The SortedSet interface in Java extends the Set interface and provides a set that
maintains its elements in ascending order. It is part of the java.util package and is
primarily implemented by the TreeSet class.
Ordered Elements: The elements in a SortedSet are maintained in sorted order,
either by their natural ordering
No Duplicates: Like other Set implementations, a SortedSet does not allow duplicate
elements.
Null Elements: In general, a SortedSet does not allow null elements. However, some
implementations like TreeSet allow one null element.
Implementation: The primary implementation of the SortedSet interface is the
TreeSet class, which is backed by a self-balancing binary search tree (Red-Black
Tree).
Sorting and Searching: Because the elements are stored in sorted order, operations
like retrieving the smallest, largest, or n-th element, as well as searching for
elements, can be performed efficiently.
Iterators and Subsets: The SortedSet interface provides methods for retrieving
iterators that traverse the set in sorted order. It also allows you to retrieve subsets of
the set based on a range of elements.
TreeSet
▪ It is implementation of the SortedSet interface in Java. It is a self-balancing
binary search tree. Elements in a TreeSet are stored in ascending order
according to their natural ordering
▪ Ordering- stores its elements in sorted ascending order.
▪ No Duplicates: TreeSet does not allow duplicate elements.
▪ Null Handling: By default, TreeSet does not allow null elements.
▪ Self-Balancing: it is a self-balancing binary search tree (Red-Black tree). This
means that after every insertion or deletion operation, the tree is rebalanced to
maintain its height within reasonable limits, ensuring logarithmic time
complexity for operations like add(), remove(), and contains().
▪ Performance: The time complexity for basic operations like add(), remove(),
and contains() is O(log n) on average, where n is the number of elements in the
set. This makes TreeSet efficient for large datasets.
Methods in TreeSet
boolean addAll(Collection c)
Adds all of the elements in the specified collection to this set.
Object clone()
Returns a shallow copy of this TreeSet instance.
Comparator comparator()
Returns the comparator used to order this sorted set, or null if this tree set uses its elements
natural ordering.
SortedSet subSet(Object fromElement, Object toElement)
Returns a view of the portion of this set whose elements range from fromElement, inclusive,
to toElement, exclusive.
Object first()
Returns the first (lowest) element currently in this sorted set.
SortedSet headSet(Object toElement)
Returns a view of the portion of this set whose elements are strictly less than toElement.
Methods in TreeSet
SortedSet tailSet(Object fromElement)
Returns a view of the portion of this set whose elements are greater than or equal to
fromElement.
boolean remove(Object o)
Removes the specified element from this set if it is present.
Object last()
Returns the last (highest) element currently in this sorted set.
void clear()
Removes all of the elements from this set.
TreeSet Example
Review questions
• What are the two ways to iterate the elements of a collection?
• What is the difference between ArrayList and Vector classes in
collection framework?
• What is the difference between HashSet and HashMap classes in
collection framework?
• Discuss the features of TreeSet class.
• Describe Set Interface and various methods given by it.
• Differentiate between HashSet and TreeSet.
• Differentiate between PriorityQueue and ArrayDeque.
• Write a java program to show union and intersection of two set
collection.