Unit 4 (JP)
Unit 4 (JP)
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.
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
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
Iterating
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
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
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
Features of ListIterator:
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
similar to Iterator.
Usage:
Enumeration<String> enumeration = vector.elements();
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.