0% found this document useful (0 votes)
6 views

Java Unit-4

notes

Uploaded by

tejaswini reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Unit-4

notes

Uploaded by

tejaswini reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Unit-4

Java Collection Framework


The Collections Framework (java.util)- Collections overview, Collection
Interfaces, The Collection classes- Array List, Linked List, Hash Set, Tree
Set, Priority Queue, Array Deque. Accessing a Collection via an Iterator,
Using an Iterator, The For-Each alternative, Map Interfaces and Classes,
Comparators, Collection algorithms, Arrays, The Legacy Classes and
Interfaces- Dictionary, Hash table, Properties, Stack, Vector More Utility
classes, String Tokenizer, Bit Set, Date, Calendar, Random, Formatter,
Scanner
Java collection framework
• Java collection framework is a collection of interfaces and classes
used to storing and processing a group of individual objects as a single
unit.
• The java collection framework holds several classes that provide a
large number of methods to store and process a group of objects.
These classes make the programmer task super easy and fast.
• Before the collection framework in java there was a set of classes like
Array, Vector, Stack, Hash Table. These classes are known as legacy
classes.
• The java collection framework contains List, Queue, Set, and Map as
top-level interfaces. The List, Queue, and Set stores single value as its
element, whereas Map stores a pair of a key and value as its element.
Java Collection Interface
• The Collection interface is the root interface for most of the interfaces
and classes of collection framework. The Collection interface is
available inside the java.util package. It defines the methods that are
commonly used by almost all the collections.
• The Collection interface extends Iterable interface.
import java.util.*;
public class CollectionInterfaceExample {
public static void main(String[] args) {
List list_1 = new ArrayList();
List<String> list_2 = new ArrayList<String>();
list_1.add(10);
list_1.add(20);
list_2.add("CMR”);
list_2.add("Technical");
list_2.add("Campus");

list_1.addAll(list_2);
System.out.println("Elements of list_1: " + list_1);

System.out.println("Search for CMR: " + list_1.contains("CMR"));


System.out.println("Search for list_2 in list_1: " + list_1.containsAll(list_2));

System.out.println("Check whether list_1 and list_2 are equal: " + list_1.equals(list_2));


System.out.println("Check is list_1 empty: " + list_1.isEmpty());

System.out.println("Size of list_1: " + list_1.size());

System.out.println("Hashcode of list_1: " + list_1.hashCode());

list_1.remove(0);
System.out.println(list_1);

list_1.retainAll(list_2);
System.out.println(list_1);

list_1.removeAll(list_2);
System.out.println(list_1);

list_2.clear();
System.out.println(list_2);
}
}
The java LIST interface:
• The List interface is a child interface of the Collection interface. The
List interface is available inside the java.util package. It defines the
methods that are commonly used by classes like ArrayList, LinkedList,
Vector, and Stack.
• The List interface extends Collection interface.
• The List interface allows duplicate elements.
• The List interface preserves the order of insertion.
• The List allows to access the elements based on the index value that
starts with zero.
import java.util.ArrayList;
import java.util.List;
public class ListInterfaceExample {
public static void main(String[] args) {
List list_1 = new ArrayList();
List<String> list_2 = new ArrayList<String>();
list_1.add(0, 10);
list_1.add(1, 20);
list_2.add(0, “csd");
list_2.add(1, “csc");
list_2.add(2, “cse");
list_1.addAll(1, list_2);
System.out.println("\nElements of list_1: " + list_1);
System.out.println("\nElement at index 3: " + list_1.get(3));
System.out.println("\nSublist : " + list_1.subList(2, 5));
list_1.set(2, 10);
System.out.println("\nAfter updating the value at index 2: " + list_1);
System.out.println("\nIndex of value 10: " + list_1.indexOf(10));
System.out.println("\nLast index of value 10: " + list_1.lastIndexOf(10));
}}
Java Queue Interface:
• The Queue interface is a child interface of the Collection interface.
The Queue interface is available inside the java.util package.
• It defines the methods that are commonly used by classes like
PriorityQueue and ArrayDeque.
• The Queue is used to organize a sequence of elements prior to the
actual operation.
• The Queue interface extends Collection interface.
• The Queue interface allows duplicate elements.
• The Queue interface preserves the order of insertion.
im p o rt ja va .u til.*;

p u b lic c la s s Qu e u e In te rfa c e Exa m p le {

p u b lic s ta tic vo id m a in (Strin g [] args) {

Qu e u e queue = n e w Prio rityQu e u e ();

queue.o ffe r(10 );


queue.o ffe r(20 );
queue.o ffe r(30 );
queue.o ffe r(40 );

Sys te m .out.p rintln ("\ n Qu e u e e le m e n ts a re - " + queue);

Sys te m .out.p rintln ("\ n He a d e le m e n t - " + queue.e le m e n t());

Sys te m .out.p rintln ("\ n He a d e le m e n t a g a in - " + queue.p e e k());

queue.re m o ve ();
Sys te m .out.p rintln ("\ n Ele m e n ts a fte r He a d re m o va l - " + queue);

queue.p o ll();
Sys te m .out.p rintln ("\ n Ele m e n ts a fte r o n e m o re He a d re m o va l - "
+ queue);

}
• The Deque interface:
is a child interface of the Queue interface. The Deque interface is
available inside the java.util package. It defines the methods that are
used by class ArrayDeque.
• The Deque interface extends Queue interface.
• The Deque interface allows duplicate elements.
• The Deque interface preserves the order of insertion.
import java.util.*;
public class DequeInterfaceExample {
public static void main(String[] args) {
Deque deque = new ArrayDeque();
deque.addFirst(10);
deque.addLast(20);
deque.offerFirst(5);
deque.offerLast(25);
deque.push(2);
System.out.println("\nElements of deque - " + deque);
System.out.println("\nFirst element - " + deque.getFirst());
System.out.println("\nLast element - " + deque.getLast());
System.out.println("\nFirst element - " + deque.peekFirst());
System.out.println("\nLast element - " + deque.peekLast());
System.out.println("\nRemove first element - " + deque.pop());
System.out.println("\nRemove one more first element - " + deque.pollFirst());
System.out.println("\nRemove last element - " + deque.pollLast());
System.out.println("\nRemove one more first element - " + deque.removeFirst());
System.out.println("\nRemove one more last element - " + deque.removeLast());
}
Java SortedSet Interface
1. Set Interface
• The Set interface is a child interface of Collection interface. It does not defines
any additional methods of it, it has all the methods that are inherited from
Collection interface.
• The Set interface does not allow duplicates. Set is a generic interface.
2. SortedSet Interface
• The SortedSet interface is a child interface of the Set interface. The SortedSet
interface is available inside the java.util package.
• It defines the methods that are used by classes HashSet, LinkedHashSet, and
TreeSet.
• The SortedSet interface extends Set interface.
• The SortedSet interface does not allow duplicate elements.
• The SortedSet interface organize the elements based on the ascending order.
• The SortedSet interface defines the following methods.
import java.util.*;
public class SortedSetInterfaceExample {
public static void main(String[] args) {
SortedSet sortedSet = new TreeSet();
sortedSet.add(10);
sortedSet.add(20);
sortedSet.add(5);
sortedSet.add(40);
sortedSet.add(30);
System.out.println("\nElements of sortedSet: " + sortedSet);
System.out.println("\nFirst element: " + sortedSet.first());
System.out.println("\nLast element: " + sortedSet.last());
System.out.println("\nSubset with upper limit: " + sortedSet.headSet(30));
System.out.println("\nSubset with lower limit: " + sortedSet.tailSet(30));
System.out.println("\nSubset with upper and lower limit: " + sortedSet.subSet(10, 30));

}
Java NavigableSet Interface:
The NavigableSet interface is a child interface of the SortedSet
interface. The NavigableSet interface is available inside the java.util
package. It defines the methods that are used by class TreeSet.
1. The NavigableSet interface extends SortedSet interface.
2. The SortedSet interface does not allow duplicate elements.
3. The SortedSet interface organize the elements based on the
ascending order.
The NavigableSet interface defines several utility methods that are used
in the TreeSet class and they are as follows.
Example

import java.util.*;
public class NavigableSetInterfaceExample {
public static void main(String[] args) {
NavigableSet navSet = new TreeSet();
navSet.add(10);
navSet.add(20);
navSet.add(5);
navSet.add(40);
navSet.add(30);
System.out.println("\nElements of sortedSet: " + navSet);
System.out.println("\nSmallest element from subSet of larger than 25: " + navSet.ceiling(25));
System.out.println("\nLargest element from subSet of smaller than 25: " + navSet.floor(25));
System.out.println("\nSmallest element from subSet of larger than 25: " + navSet.higher(25));
System.out.println("\nLargest element from subSet of smaller than 25: " + navSet.lower(25));
System.out.println("\nSubset with upperBound, including it: " + navSet.headSet(30, true));
System.out.println("\nSubset with upperBound, excluding it: " + navSet.headSet(30, false));
System.out.println("\nSubset with lowwerBound, including it: " + navSet.tailSet(30, true));
System.out.println("\nSubset with lowerBound, excluding it: " + navSet.tailSet(30, false));
System.out.println("\nRemove the first element: " + navSet.pollFirst());
System.out.println("\nRemove the last element: " + navSet.pollLast());

}
• Java ArrayList Class
• The ArrayList class is a part of java collection framework. It is available inside
the java.util package. The ArrayList class extends AbstractList class and
implements List interface.
• The elements of ArrayList are organized as an array internally. The default size
of an ArrayList is 10.
• The ArrayList class is used to create a dynamic array that can grow or shrunk
as needed.
1. The ArrayList is a child class of AbstractList
2. The ArrayList implements interfaces like List, Serializable, Cloneable, and
RandomAccess.
3. The ArrayList allows to store duplicate data values.
4. The ArrayList allows to access elements randomly using index-based
accessing.
5. The ArrayList maintains the order of insertion.
ArrayList class declaration
• The ArrayList class has the following declaration.
Example
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable,
Serializable
• ArrayList class constructors
• The ArrayList class has the following constructors.
• ArrayList( ) - Creates an empty ArrayList.
• ArrayList(Collection c) - Creates an ArrayList with given collection of elements.
• ArrayList(int size) - Creates an empty ArrayList with given size (capacity).
Operations on ArrayList
The ArrayList class allow us to perform several operations like adding, accesing, deleting,
updating, looping, etc. Let's look at each operation with examples.
• Adding Items
• The ArrayList class has the following methods to add items.
• boolean add(E element) - Appends given element to the ArrayList.
• boolean addAll(Collection c) - Appends given collection of elements to the ArrayList.
• void add(int index, E element) - Inserts the given element at specified index.
• boolean addAll(int index, Collection c) - Inserts the given collection of elements at specified
index.
an example program to illustrate adding items to the ArrayList.
Example:
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list_1 = new ArrayList<String>();
ArrayList list_2 = new ArrayList();
//Appending
list_1.add(“CMR");
System.out.println("list_1: " + list_1);
list_1.add(“CAMPUS");
System.out.println("list_1: " + list_1);
//Inserting at specified index
list_1.add(1, “TECHNICAL");
System.out.println("list_1: " + list_1);
//Appending a collection of elements
list_2.addAll(list_1);
System.out.println("list_2: " + list_2);
//Inserting collection of elements at specified index
list_2.addAll(2, list_1);
System.out.println("list_2: " + list_2);
}
Accessing Items
• The ArrayList class has the following methods to access items.
• E get(int index) - Returns element at specified index from the
ArrayList.
• ArrayList subList(int startIndex, int lastIndex) - Returns an ArrayList
that contails elements from specified startIndex to lastIndex-1 from
the invoking ArrayList.
• int indexOf(E element) - Returns the index value of given element first
occurence in the ArrayList.
• int lastIndexOf(E element) - Returns the index value of given element
last occurence in the ArrayList.
import java.util.*;
public class ArrayListExample {

public static void main(String[] args) {

ArrayList<String> list_1 = new ArrayList<String>();

list_1.add(“CMR");
list_1.add(“TECHNICAL ");
list_1.add("CAMPUS");
list_1.add("-");
list_1.add("Java");
list_1.add("Tutorial");
list_1.add("Class");

System.out.println("Element at index 4 is " + list_1.get(4));


System.out.println("Sublist from index 1 to 4: " + list_1.subList(1, 5));
System.out.println("Index of element \"Class\" is " + list_1.indexOf("Class"));
System.out.println("Last index of element \"Class\" is " + list_1.lastIndexOf("Class"));

}
}
• Updating Items
• The ArrayList class has the following methods to update or change
items.
• E set(int index, E newElement) - Replace the element at specified
index with newElement in the invoking ArrayList.
• ArrayList replaceAll(UnaryOperator e) - Replaces each element of
invoking ArrayList with the result of applying the operator to that
element.
Example
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list_1 = new ArrayList<String>();
list_1.add(“CMR");
list_1.add(“TECHNICAL");
list_1.add("CAMPUS");
list_1.add("-");
list_1.add("Java");
list_1.add("Tutorial");
list_1.add("Class");
System.out.println("\nList before update: " + list_1);
list_1.set(3, ":");
System.out.println("\nList after update: " + list_1);
list_1.replaceAll(e -> e.toUpperCase());
System.out.println("\nList after update: " + list_1);

}
}
• Removing Items
The ArrayList class has the following methods to remove items.
• E remove(int index) - Removes the element at specified index in
the invoking ArrayList.
• boolean remove(Object element) - Removes the first occurence
of the given element from the invoking ArrayList.
• boolean removeAll(Collection c) - Removes the given collection
of elements from the invoking ArrayList.
• void retainAll(Collection c) - Removes all the elements except the
given collection of elements from the invoking ArrayList.
• boolean removeIf(Predicate filter) - Removes all the elements
from the ArrayList that satisfies the given predicate.
• void clear( ) - Removes all the elements from the ArrayList.
Java LinkedList Class
• The LinkedList class is a part of java collection framework. It is available
inside the java.util package. The LinkedList class extends
AbstractSequentialList class and implements List and Deque interface.
• The elements of LinkedList are organized as the elements of linked list
data structure.
• The LinkedList class is used to create a dynamic list of elements that can
grow or shrunk as needed.
• The LinkedList is a child class of AbstractSequentialList
• The LinkedList implements interfaces like List, Deque, Cloneable, and
Serializable.
• The LinkedList allows to store duplicate data values.
• The LinkedList maintains the order of insertion.
LinkedList class constructors
The LinkedList class has the following constructors.
• LinkedList( ) - Creates an empty List.
• LinkedList(Collection c) - Creates a List with given collection of elements.
Operations on LinkedList
The LinkedList class allow us to perform several operations like adding, accesing, deleting, updating, looping, etc.
Let's look at each operation with examples.
Adding Items
The LinkedList class has the following methods to add items.
• boolean add(E element) - Appends given element to the List.
• boolean addAll(Collection c) - Appends given collection of elements to the List.
• void add(int position, E element) - Inserts the given element at specified position.
• boolean addAll(int position, Collection c) - Inserts the given collection of elements at specified position.
• void addFirst(E element) - Inserts the given element at beggining of the list.
• void addLast(E element) - Inserts the given element at end of the list.
• boolean offer(E element) - Inserts the given element at end of the list.
• boolean offerFirst(E element) - Inserts the given element at beggining of the list.
• boolean offerLast(E element) - Inserts the given element at end of the list.
• void push(E element) - Inserts the given element at beggining of the list.
im p o rt ja va .u t il.*;

p u b lic c la s s Lin ke d Lis t Exa m p le {

p u b lic s t a tic vo id m a in (St rin g [] args) {

Lin ke d Lis t <St rin g > list_1 = n e w Lin ke d Lis t <St rin g >();
Lin ke d Lis t list_2 = n e w Lin ke d Lis t ();

list_2.a d d (10 );
list_2.a d d (20 );
list_2.a d d Firs t (5);
list_2.a d d La s t (25);
list_2.o ffe r(2);
list_2.o ffe rFirs t (1);
list_2.o ffe rLa s t (10 );
list_2.p u s h (40 );

list_1.a d d All(list_2);

Sys t e m .out.p rin t ln ("Lis t _1: " + list_1);

Sys t e m .out.p rin t ln ("Lis t _2: " + list_2);

}
Accessing Items
The LinkedList class has the following methods to access items.
• E get(int position) - Returns element at specified position from the LinkedList.
• E element( ) - Returns the first element from the invoking LinkedList.
• E getFirst( ) - Returns the first element from the invoking LinkedList.
• E getLast( ) - Returns the last element from the invoking LinkedList.
• E peek( ) - Returns the first element from the invoking LinkedList.
• E peekFirst( ) - Returns the first element from the invoking LinkedList, and returns null
if list is empty.
• E peekLast( ) - Returns the last element from the invoking LinkedList, and returns null
if list is empty.
• int indexOf(E element) - Returns the index value of given element first occurence in
the LinkedList.
• int lastIndexOf(E element) - Returns the index value of given element last occurence in
the LinkedList.
• E pop( ) - Returns the first element from the invoking LinkedList.
im p o rt ja va .util.*;

p ub lic c la s s Linke d Lis tExa m p le {

p ub lic s ta tic vo id m a in(String [] args) {

Linke d Lis t list_1 = ne w Linke d Lis t();

fo r(int i = 1; i <= 10 ; i++)


list_1.a d d (i);

Sys te m .out.p rintln("Lis t is " + list_1 + "\ n");

Sys te m .out.p rintln("g e t(p o s itio n) - " + list_1.g e t(3));


Sys te m .out.p rintln("g e tFirs t() - " + list_1.g e tFirs t());
Sys te m .out.p rintln("g e tLa s t() - " + list_1.g e tLa s t());
Sys te m .out.p rintln("e le m e nt() - " + list_1.e le m e nt());
Sys te m .out.p rintln("p e e k() - " + list_1.p e e k());
Sys te m .out.p rintln("p e e kFirs t() - " + list_1.p e e kFirs t());
Sys te m .out.p rintln("p e e kLa s t() - " + list_1.p e e kLa s t());
Sys te m .out.p rintln("p o p () - " + list_1.p o p ());
Sys te m .out.p rintln("ind e xOf(e le m e nt) - " + list_1.ind e xOf(5));
Sys te m .out.p rintln("la s tInd e xOf(e le m e nt) - " +
list_1.la s tInd e xOf(5));

}
Java PriorityQueue Class
• The Priority Queue class is a part of java collection framework. It is
available inside the java.util package. The Priority Queue class extends
AbstractQueue class and implements Serializable interface.
• The elements of Priority Queue are organized as the elements of
queue data structure, but it does not follow FIFO principle. The
Priority Queue elements are organized based on the priority heap.
1. The Priority Queue is a child class of AbstractQueue
2. The Priority Queue implements interface Serializable.
3. The Priority Queue allows to store duplicate data values, but not
null values.
4. The Priority Queue maintains the order of insertion.
5. The Priority Queue used priority heap to organize its elements.
PriorityQueue class constructors
• The PriorityQueue class has the following constructors.
• PriorityQueue( ) - Creates an empty PriorityQueue with the default initial
capacity (11) that orders its elements according to their natural ordering.
• PriorityQueue(Collection c) - Creates a PriorityQueue with given
collection of elements.
• PriorityQueue(int initialCapacity) - Creates an empty PriorityQueue with
the specified initial capacity.
• PriorityQueue(int initialCapacity, Comparator comparator) - Creates an
empty PriorityQueue with the specified initial capacity that orders its
elements according to the specified comparator.
• PriorityQueue(PriorityQueue pq) - Creates a PriorityQueue with the
elements in the specified priority queue.
• PriorityQueue(SortedSet ss) - Creates a PriorityQueue with the elements
in the specified SortedSet
Let's consider an example program to illustrate adding items to the PriorityQueue.
Example
import java.util.*;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue queue = new PriorityQueue();
PriorityQueue anotherQueue = new PriorityQueue();
queue.add(10);
queue.add(20);
queue.add(15);
System.out.println("\nQueue is " + queue);
anotherQueue.addAll(queue);
System.out.println("\nanotherQueue is " + anotherQueue);
anotherQueue.offer(25);
System.out.println("\nanotherQueue is " + anotherQueue);

}
Map Interface in java
• The java collection framework has an interface Map that is available
inside the java.util package. The Map interface is not a subtype of
Collection interface.
• The Map stores the elements as a pair of key and value.
• The Map does not allows duplicate keys, but allows duplicate values.
• In a Map, each key can map to at most one value only.
• In a Map, the order of elements depends on specific
implementations, e.g TreeMap and LinkedHashMap have predictable
order, while HashMap does not.

You might also like