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

Unit IV-OOP Java-Part I

The document discusses the Java Collections Framework (JCF) and highlights the limitations of arrays compared to collections, such as fixed size and lack of built-in methods. It explains various interfaces within the JCF, including Collection, List, Set, Queue, and Map, and their respective functionalities. Additionally, it covers the ArrayList class, its properties, methods, and differences from arrays, emphasizing its dynamic resizing capabilities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Unit IV-OOP Java-Part I

The document discusses the Java Collections Framework (JCF) and highlights the limitations of arrays compared to collections, such as fixed size and lack of built-in methods. It explains various interfaces within the JCF, including Collection, List, Set, Queue, and Map, and their respective functionalities. Additionally, it covers the ArrayList class, its properties, methods, and differences from arrays, emphasizing its dynamic resizing capabilities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Java Collections Framework

Problems with Arrays:

1. Fixed in Size: Once we create an array with some size there is no chance of increasing or
decreasing the size of that array based on our requirement.
2. Hold Homogeneous Elements: Arrays can hold only homogeneous type of elements.
Note:We can solve this problem by using object type arrays.
Object[]a=newObject(10000);
a[0]=newStudent();-(valid)
a[1]=newCustomer();-- (valid)
3. No Readymade Method Support: Arrays are not implemented based on some standard data
structure. So, it is developer’s responsibility to write the code for every requirement like storing
the elements based on some sorting order, search for an element is there or not in the array etc.
4. To use arrays, it is better to know the size in advance, which is may not possible always.
Note:If we know the size in advance, then it is highly recommended to go for arrays.
Because performance wise arrays are better than collections.
Ex:
al 1 2 …………… 1 Crore

Index 0 1 ………. 9999999


Suppose, we have 1 Crore elements in an ArrayList. If we want to insert a new element, then a
new ArrayList is created with 1Cr + 1 size, all 1Cr elements are copied from old ArrayList to new
ArrayList with the same reference variable (al), now the old object is eligible for garbage collection
and the new element is inserted to new ArrayList. It takes huge amount of time.

Java Collection Framework (JCF):


• Collection framework defines several interfaces and classes which can be used to
represent a group of individual objects as a single entity (i.e. collection).
• The Java collections framework provides a set of interfaces and classes to implement various data
structures and algorithms.
For example, the LinkedList class of the collections framework provides the implementation of the doubly-linked
list data structure.

Collection (I):Collection is a group of individual objects as a single entity. Collection is an


interface which is used to represent a group of individual objects as a single entity.

Collections(C): Collections is a utility class presents in java.util package to define several utility
methods like sorting, searching etc. in collection objects.
Ex:To sort an ArrayList Collections.sort(al);al ArrayListObject

Arrays vs Collections:

Arrays Collections
1.Array are fixed in size. 1.Collections are growable in nature.

2.W.r.t memory arrays are not 2.W.r.t memory collections are recommended.
recommended.
3.W.r.t performance arrays are 3.W.r.t performance collections are not
recommended. recommended.

4.Arrays can hold only homogeneous 4.Collections can hold both homogeneous and
elements. heterogeneous elements.

5.Arrays are not implemented based on any 5.Every collection class is implemented based on some
DS. So, readymade method support is not standard DS. So, readymade method support is
available. available.

6.Arrays can hold primitive types and 6.Collections can hold only reference types(objects).
Reference types(objects).
7.There are no predefined classes in Java API 7.There are so many predefined classes are available in
which represents arrays. Java API (java.util package) which represents
collections.
Interfaces of Java Collections FrameWork (JCF)

The Java collections framework provides various interfaces. These interfaces include several methods to
perform different operations on collections.

Java Collection Interface

Collection interface is used to represent a group of individual objects as a single entity. It defines the most
common methods which are applicable for many collection objects.
The Collection interface is the root interface of the collections framework hierarchy.
Java does not provide direct implementations of the Collection interface but provides implementations of its
subinterfaces like List, Set, and Queue.
Collections Framework Vs. Collection Interface

The Collection interface is the root interface of the collections framework. The framework includes other
interfaces as well: Map and Iterator. These interfaces may also have subinterfaces.

Subinterfaces of the Collection Interface

As mentioned earlier, the Collection interface includes subinterfaces that are implemented by Java classes.
All the methods of the Collection interface are also present in its subinterfaces.
Here are the subinterfaces of the Collection Interface:
List Interface
The List interface is an ordered collection that allows us to add and remove elements like
an array. List is the child interface of Collection interface. If we want to represent a group of
individual objects as single entity where duplicates are allowed and insertion order must be
preserved, then we go for List.

Set Interface
The Set interface allows us to store elements in different sets similar to the set in mathematics.
It cannot have duplicate elements. Set is the child interface of Collection interface. If we want
to represent a group of individual objects as single entity where duplicates are not allowed and
insertion order not preserved, then we go for Set.

Queue Interface

The Queue interface is used when we want to store and access elements in First In, First Out manner. Queue
is the child interface of Collection. If we want to represent a group of individual objects prior to processing,
then we should go for Queue

Java Map Interface


In Java, the Map interface allows elements to be stored in key/value pairs. Keys are unique
names that can be used to access a particular element in a map. And, each key has a single
value associated with it. Map is not child interface of Collection. If we want represent a group
of objects as key value pairs ten we should go for Map interface.

Key Value
entry
101 A
102 B
103 C
104 A

Both keys and values are objects only. Duplicate keys are not allowed but duplicate values are
allowed. Each key value pair is called entry. Hence, Map is considered as a collection of entry
objects.
Java Iterator Interface

In Java, the Iterator interface provides methods that can be used to access elements of collections.

Why the Collections Framework?

The Java collections framework provides various data structures and algorithms that can be used directly. This
has two main advantages:

• We do not have to write code to implement these data structures and algorithms manually.

• Our code will be much more efficient as the collections framework is highly optimized.

Moreover, the collections framework allows us to use a specific data structure for a particular type of data.
Here are a few examples,

• If we want our data to be unique, then we can use the Set interface provided by the collections framework.
• To store data in key/value pairs, we can use the Map interface.
• The ArrayList class provides the functionality of resizable arrays.

Methods of Collection

The Collection interface includes various methods that can be used to perform different operations on objects.
These methods are available in all its subinterfaces.

Difference between removeAll() and clear()

removeAll() clear()
1.The removeAll() method removes the elements 1.The clear() method blindly removes all theelements
of a collection by comparing with the elements of from a collection.
other collection.
2.The return type is boolean. 2.The return type is void.

3.To perform removeAll() we require two 3.To perform clear() we require only one collection
Collection objects. object.
4.The removeAll() is slower than clear(). 4.The clear() is faster than removeAll().
5.If we observe the implementation of 5.If we observe the implementation of clear(), the time
removeAll(), the time complexity is O(n2). complexity is O(n).

6. Choose ‘removeAll()’ when you want toremove 6. Choose ‘clear()’ method when you want to remove
only certain elements from the collection by all elements from the collection without any cross
comparing with other collection. checks.
Java List

In Java, the List interface is an ordered collection that allows us to store and access elements sequentially. It
extends the Collection interface.

List(I): List is the child interface of Collection interface. If we want to represent a group of
individual objects as single entity where duplicates are allowed and insertion order must be
preserved, then we go for List.

Classes that Implement List

Since List is an interface, we cannot create objects from it.


In order to use the functionalities of the List interface, we can use these classes:
• ArrayList
• LinkedList
• Vector
• Stack

Methods of List

The List interface includes all the methods of the Collection interface. Its because Collection is a super
interface of List.
Some of the commonly used methods of the Collection interface that's also available in the List interface are:
Methods Description

add() adds an element to a list

addAll() adds all elements of one list to another

get() helps to randomly access elements from lists


returns iterator object that can be used to sequentially access elements of
iterator()
lists

set() changes elements of lists

remove() removes an element from the list

removeAll() removes all the elements from the list

clear() removes all the elements from the list (more efficient than removeAll())

size() returns the length of lists

toArray() converts a list into an array

contains() returns true if a list contains specific element

Implementation of the List Interface

1. Implementing the ArrayList Class


import java.util.List;
import java.util.ArrayList;

class Main {

public static void main(String[] args) {


// Creating list using the ArrayList class
List<Integer> numbers = new ArrayList<>();

// Add elements to the list


numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("List: " + numbers);

// Access element from the list


int number = numbers.get(2);
System.out.println("Accessed Element: " + number);

// Remove element from the list


int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
}
}

Output

List: [1, 2, 3]
Accessed Element: 3
Removed Element: 2

2. Implementing the LinkedList Class


import java.util.List;
import java.util.LinkedList;

class Main {

public static void main(String[] args) {


// Creating list using the LinkedList class
List<Integer> numbers = new LinkedList<>();

// Add elements to the list


numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("List: " + numbers);

// Access element from the list


int number = numbers.get(2);
System.out.println("Accessed Element: " + number);

// Using the indexOf() method


int index = numbers.indexOf(2);
System.out.println("Position of 3 is " + index);

// Remove element from the list


int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
}
}
Run Code
Output

List: [1, 2, 3]
Accessed Element: 3
Position of 3 is 1
Removed Element: 2

1. Java ArrayList

In Java, we use the ArrayList class to implement the functionality of resizable-arrays.


It implements the List interface of the collections framework .
Java ArrayList Vs Array

In Java, we need to declare the size of an array before we can use it. Once the size of an array is declared, it's
hard to change it.
To handle this issue, we can use the ArrayList class. It allows us to create resizable arrays.
Unlike arrays, arraylists can automatically adjust their capacity when we add or remove elements from them.
Hence, arraylists are also known as dynamic arrays.

ArrayList(C): ArrayList is a class presents in java.util package which extends(inherits) from


AbstractList class and implements from List, RandomAccess, Cloneable and Serializable
interfaces.
i) Properties:
 The underlying DS is resizable array or growable array.
 Duplicates are allowed and Insertion order is preserved.
 Heterogeneous elements are allowed and null insertion is possible.
 ArrayList is the best choice if our frequent operation is retrieval operation
because ArrayList implements RandomAccess interface and ArrayList is the worst
choice if our frequent operation is insertion or deletion in the middle because
several shift operations will take huge amount of time.
Note:Except TreeSet and TreeMap everywhere heterogeneous elements are allowed.

Creating an ArrayList

Before using ArrayList, we need to import the java.util.ArrayList package first.


• creating arraylists in Java:

ArrayList<Type> arrayList= new ArrayList<>();

Type indicates the type of an arraylist. For example,

// create Integer type arraylist


ArrayList<Integer> al1 = new ArrayList<>();

// create String type arraylist


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

In the above program, we have used Integer not int. It is because we cannot use primitive types while creating
an arraylist. Instead, we have to use the corresponding wrapper classes.
Here, Integer is the corresponding wrapper class of int

Basic Operations on ArrayList

The ArrayList class provides various methods to perform different operations on arraylists. We will look at
some commonly used arraylist operations in this tutorial:
• Add elements

• Access elements

• Change elements

• Remove elements

Already add(), get(), set(), and remove() method of the ArrayList class are there

Besides these basic methods, here are some more ArrayList methods that are commonly used.
Methods Descriptions

size() Returns the length of the arraylist.

sort() Sort the arraylist elements.

clone() Creates a new arraylist with the same element, size, and capacity.

Searches the arraylist for the specified element and returns a boolean
contains()
result.

ensureCapacity() Specifies the total element the arraylist can contain.

isEmpty() Checks if the arraylist is empty.

Searches a specified element in an arraylist and returns the index of


indexOf()
the element.

Example:
import java.util.ArrayList;

class Main {
public static void main(String[] args) {

// creating an array list


ArrayList<String> animals = new ArrayList<>();
animals.add("Cow");
animals.add("Cat");
animals.add("Dog");
System.out.println("ArrayList: " + animals);
// get the element from the arraylist
String str = animals.get(1);

System.out.print("Element at index 1: " + str);

// remove element from index 2


String str1 = animals.remove(2);

System.out.println("Updated ArrayList: " + animals);


System.out.println("Removed Element: " + str1);

// change the element of the array list


animals.set(1, "Horse");

// iterate using for-each loop


System.out.println("Accessing individual elements: ");

for (String l : animals) {


System.out.print(l);
System.out.print(", ");
}

}
}
Output

ArrayList: [Cow, Cat, Dog]


Element at index 1: Cat
Updated ArrayList: [Cow, Cat]
Removed Element: Dog
Accessing individual elements:
Cow, Horse

• To add a single element to the arraylist, we use the add() method of the ArrayList class.
• In the above example, we have used the get() method with parameter 1. Here, the method returns the
element at index 1.
• Here, the set() method changes the element at index 2
• Here, the remove() method takes the index number as the parameter. And, removes the element
specified by the index number.
• We can use the Java for-each loop to loop through each element of the arraylist.
ii) Declaration:
Public classArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneab le,
Serializable

iii) Constructors:
(a) ArrayList al=new ArrayList();
Creates an empty ArrayList with default initial capacity 10. Once
ArrayList reaches its maximum capacity then a new ArrayList will be
created with
newcapacity=(currentcapacity*3/2)+1
& with same reference variable(al).
(b) ArrayList al = new ArrayList(int initial_capacity);
Creates an empty ArrayList with specified initial
capacity.
(c) ArrayList al=new ArrayList(Collection c);
Creates an equivalent ArrayList for the given Collection.

ArrayList vs Vector:
ArrayList Vector
1.Every method present in the ArrayList is 1.Every method present in the Vector is synchronized.
non-synchronized.
2.At a time, multiple threads can operate on 2.At a time, only one thread allowed to operate on single
Single ArrayList object and hence it is not vector object and hence it is thread safe.
thread safe.
3.Relatively performance is high because 3.Relatively performance is low because threads are
threads are not required to wait to operate on required to wait to operate on Vector object.
ArrayList object.
4.Introduced in 1.2 version and it is non legacy 4.Introduced in1.0 version and it is legacy.

2. Java LinkedList class

LinkedList(C)

Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data structure. It
inherits the AbstractList class and implements List and Deque interfaces. LinkedList is a class presents in
java.util package.

Properties:
The underlying DS is Doubly LinkedList.
Duplicates are allowed and Insertion order is preserved.
Heterogeneous elements are allowed and null insertion is possible.
If our frequent operation is insertion or deletion in the middle, then LinkedList is
the best choice. Because the internal structure of the LinkedList. LinkedList is the
worst choice if our frequent operation is retrieval operation.
Constructors:
(a) LinkedList ll=new LinkedList(); Creates an empty LinkedList object
(b) LinkedList l2=new LinkedList(Collection c);
Creates an equivalent LinkedList object for the given Collection.
Methods of LinkedList:

Note: Usually LinkedList is used to develop Stacks and Queues.

ArrayList vs LinkedList:
ArrayList LinkedList
1.ArrayList internally uses resizable array or 1.LinkedList internally uses doubly linked list to store
dynamic array to store the elements. the elements.
2. Manipulation with ArrayList is slow because it 2.Manipulation with LinkedList is faster than ArrayList
internally uses array. If any element is removed because it uses doubly linked list so no bit shifting is
from the array, all the bits are shifted in required in memory.
memory.
3.ArrayList class can act as a list only because it 3.LinkedList class can act as a list and queue both
Implements List only. Because it implements List and Deque interfaces.
4.ArrayList is the best choice if our frequent 4.LinkedList is the best choice if our frequent operation
Operation is retrieval. Is insertion or deletion in the middle.
5. In ArrayList elements are stored in 5.In LinkedList elements are not stored in consecutive
Consecutive memory locations. Memory locations.

Java LinkedList example to add/remove elements


import java.util.*;
public class MyLinkedList {

public static void main(String [] args)


{
LinkedList<String> ll=new LinkedList<String>();
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
ll.add("Anuj");
ll.add("Gaurav");
ll.add("Harsh");
ll.add("Virat");
ll.add("Gaurav");
ll.add("Harsh");
ll.add("Amit");
System.out.println("Initial list of elements: "+ll);
//Removing specific element from arraylist
ll.remove("Vijay");
System.out.println("After invoking remove(object) method: "+ll);
//Removing element on the basis of specific position
ll.remove(0);
System.out.println("After invoking remove(index) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Ravi");
ll2.add("Hanumat");
// Adding new elements to arraylist
ll.addAll(ll2);
System.out.println("Updated list : "+ll);
//Removing all the new elements from arraylist
ll.removeAll(ll2);
System.out.println("After invoking removeAll() method: "+ll);
//Removing first element from the list
ll.removeFirst();
System.out.println("After invoking removeFirst() method: "+ll);
//Removing first element from the list
ll.removeLast();
System.out.println("After invoking removeLast() method: "+ll);
//Removing first occurrence of element from the list
ll.removeFirstOccurrence("Gaurav");
System.out.println("After invoking removeFirstOccurrence() method: "+ll);
//Removing last occurrence of element from the list
ll.removeLastOccurrence("Harsh");
System.out.println("After invoking removeLastOccurrence() method: "+ll);

//Removing all the elements available in the list


ll.clear();
System.out.println("After invoking clear() method: "+ll);
}
}
Output:
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav, Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []

Java LinkedList Example to reverse a list of elements


import java.util.*;
public class LinkedList4{
public static void main(String args[]){

LinkedList<String> ll=new LinkedList<String>();


ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
//Traversing the list of elements in reverse order
Iterator i=ll.descendingIterator();
while(i.hasNext())
{
System.out.println(i.next());
}

}
}
Output: Ajay
Vijay
Ravi

Java Vector

Vector(C): The Vector class is an implementation of the List interface that allows us to create
resizable-arrays similar to the ArrayList class. Vector is a class presents in java.util package
which extends(inherits) from AbstractList class and implements from List interfaces.
Properties:
 The underlying DS is resizable array or growable array.
 Duplicates are allowed and Insertion order is preserved.
 Heterogeneous elements are allowed and null insertion is possible.
 Every method present in the vector is synchronized and hence vector object is
thread safe.
Declaration:
Public class Vector<E> extends AbstractList<E> implements List<E>

Constructors:
(a) Vector v = new Vector();
Creates an empty vector object with default initial capacity 10. Once Vector reaches its
max capacity then a new vector will be crated with (double) capacity = current
capacity*2.
(b) Vector v =new Vector(int initial_capacity);
Creates an empty Vector object with specified initial capacity.
(c) Vector v =new Vector(Collection c);
Creates an equivalent vector object for the given Collection. This constructor
meant for inter conversion between collection objects.
Methods of Vector:
To add objects
• add(element) - adds an element to vectors
• add(index, element) - adds an element to the specified position
• addAll(vector) - adds all elements of a vector to another vector
To remove objects
• remove(index) - removes an element from specified position
• removeAll() - removes all the elements
• clear() - removes all elements. It is more efficient than removeAll()
To get objects
• get(index) - returns an element specified by the index
• iterator() - returns an iterator object to sequentially access vector elements
Other Methodss
Methods Descriptions

set() changes an element of the vector

size() returns the size of the vector

toArray() converts the vector into an array

toString() converts the vector into a String

contains() searches the vector for specified element and returns a boolean result
Example:
import java.util.Vector;

class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");

System.out.println("Initial Vector: " + animals);

// Using get()
String element = animals.get(2);
System.out.println("Element at index 2: " + element);

// Using remove()
String element = animals.remove(1);
System.out.println("Removed Element: " + element);
System.out.println("New Vector: " + animals);

// Using clear()
animals.clear();
System.out.println("Vector after clear(): " + animals);
}
}
Output

Initial Vector: [Dog, Horse, Cat]


Element at index 2: Cat
New Vector: [Dog, Cat]
Vector after clear(): []

Java Stack Class

The Java collections framework has a class named Stack that provides the functionality of the
stack data structure. Stack is a class presents in java.util package which extends from Vector
class. So, it is the child class of Vector and it is a specially designed for last-in-first-out (LIFO)
order.
The Stack class extends the Vector class.

Stack Implementation

In stack, elements are stored and accessed in Last In First Out manner. That is, elements are added to the top
of the stack and removed from the top of the stack.
Declaration: Public class Stack<E> extends Vector<E>

Creating a Stack

In order to create a stack, we must import the java.util.Stack package first. Once we import the package, here
is how we can create a stack in Java.

Stack<Type> stacks = new Stack<>();

// Create Integer type stack


Stack<Integer> stacks = new Stack<>();
// Create String type stack
Stack<String> stacks = new Stack<>();

Constructors: Stack s=new Stack();


Methods of Stack:
(a) Object push(Object o) –To insert an object into the Stack
(b) Object pop(Object o)–To remove an object and return the top of the Stack
(c) Object peek()– To return top of the Stack without removal
(d) Boolean empty()–Returns true if the Stack is empty
(e) Int search(Object o)–Returns offset if the element is available otherwise returns -1
import java.util.Stack;

class Main {
public static void main(String[] args) {
Stack<String> s= new Stack<>();

// Add elements to Stack


s.push("A");
s.push("B");
s.push("C);
System.out.println("Initial Stack: " + s);
// Remove element from stack
String e = s.pop();
System.out.println("Stack: " + s);
//Access elt from top
String e2 = s.peek();
System.out.println("Element at top: " + e2);
}
}

Ex: Stack s=new Stack();


s.push(“A”); offset index
s.push(“B”); 1 C 2
s.push(“C”);
SOP(s);//[A,B, C] 2 B 1
SOP(s.search(‘A’));//3 3 0
A
SOP(s.search(‘Z’));//-1 Stack
llectionthenw
Java Queue Interface

Queue(I): Queue is the child interface of Collection. If we want to represent a group of individual
objects prior to processing, then we should go for Queue. For example, before sending SMS
messages all mobile numbers we have to store in some DS. In which order we added mobile
numbers in the same order only messages should be delivered. For this FIFO requirement Queue
is the best choice.

Classes that Implement Queue

Since the Queue is an interface, we cannot provide the direct implementation of it.
In order to use the functionalities of Queue, we need to use classes that implement it:
• ArrayDeque
• LinkedList
• PriorityQueue

Interfaces that extend Queue

The Queue interface is also extended by various subinterfaces:


• Deque
• BlockingQueue
• BlockingDeque

Working of Queue Data Structure

In queues, elements are stored and accessed in First In, First Out manner. That is, elements are added from the
behind and removed from the front.
Usually Queue follows FIFO order but based on our requirement we can implement our own
priority order also (Priority Queue). LinkedList class also implements Queue interface. LinkedList
based implementation of Queue always follows FIFO order.
In Java, we must import java.util.Queue package in order to use Queue.

// LinkedList implementation of Queue


Queue<String> animal1 = new LinkedList<>();

// Array implementation of Queue


Queue<String> animal2 = new ArrayDeque<>();

// Priority Queue implementation of Queue


Queue<String> animal 3 = new PriorityQueue<>();

Here, we have created objects animal1, animal2 and animal3 of


classes LinkedList, ArrayDeque and PriorityQueue respectively. These objects can use the functionalities of
the Queue interface.

Methods of Queue

The Queue interface includes all the methods of the Collection interface. It is because Collection is the super
interface of Queue.
Some of the commonly used methods of the Queue interface are:
• add() - Inserts the specified element into the queue. If the task is successful, add() returns true, if not it
throws an exception.
• offer() - Inserts the specified element into the queue. If the task is successful, offer() returns true, if not it
returns false.
• element() - Returns the head of the queue. Throws an exception if the queue is empty.
• peek() - Returns the head of the queue. Returns null if the queue is empty.
• remove() - Returns and removes the head of the queue. Throws an exception if the queue is empty.
• poll() - Returns and removes the head of the queue. Returns null if the queue is empty.
Implementation of the Queue Interface

1. Implementing the LinkedList Class


import java.util.Queue;
import java.util.LinkedList;

class Main {

public static void main(String[] args) {


// Creating Queue using the LinkedList class
Queue<Integer> numbers = new LinkedList<>();

// offer elements to the Queue


numbers.offer(1);
numbers.offer(2);
numbers.offer(3);
System.out.println("Queue: " + numbers);

// Access elements of the Queue


int accessedNumber = numbers.peek();
System.out.println("Accessed Element: " + accessedNumber);

// Remove elements from the Queue


int removedNumber = numbers.poll();
System.out.println("Removed Element: " + removedNumber);

System.out.println("Updated Queue: " + numbers);


}
}
Run Code
Output

Queue: [1, 2, 3]
Accessed Element: 1
Removed Element: 1
Updated Queue: [2, 3]

Priority Queue(C): Priority Queue is a class presents in java.util package which extends(inherits)
from AbstractQueue class. If we want to represent a group of individual objects prior to processing
according to some priority, then we should go for PriorityQueue. The priority can be either default
natural sorting order or customized sorting order defined by Comparator.

i) Properties:
 Insertion order is not preserved and it is based on some priority.
 Duplicate objects are not allowed.
 Implementing the PriorityQueue Class
 import java.util.Queue;
 import java.util.PriorityQueue;

 class Main {

 public static void main(String[] args) {
 // Creating Queue using the PriorityQueue class
 Queue<Integer> numbers = new PriorityQueue<>();

 // offer elements to the Queue
 numbers.offer(5);
 numbers.offer(1);
 numbers.offer(2);
 System.out.println("Queue: " + numbers);

 // Access elements of the Queue
 int accessedNumber = numbers.peek();
 System.out.println("Accessed Element: " + accessedNumber);

 // Remove elements from the Queue
 int removedNumber = numbers.poll();
 System.out.println("Removed Element: " + removedNumber);

 System.out.println("Updated Queue: " + numbers);
 }
 }
 Run Code

 Output

 Queue: [1, 5, 2]
 Accessed Element: 1
 Removed Element: 1
 Updated Queue: [2, 5]

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