Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
58 views

Java Collection (Java - Util.class) : Content

The document discusses the ArrayDeque class in Java. It provides 3 key points: 1. ArrayDeque provides a resizable-array implementation of the Deque interface that allows adding/removing from both ends. It has no capacity limits and grows dynamically. 2. Common operations run in amortized constant time, while some like remove run in linear time. Iterators are fail-fast if the deque is modified during iteration. 3. The document describes common ArrayDeque methods like add(), addFirst(), clear(), clone(), and their usage through examples.

Uploaded by

Shubham manjhi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Java Collection (Java - Util.class) : Content

The document discusses the ArrayDeque class in Java. It provides 3 key points: 1. ArrayDeque provides a resizable-array implementation of the Deque interface that allows adding/removing from both ends. It has no capacity limits and grows dynamically. 2. Common operations run in amortized constant time, while some like remove run in linear time. Iterators are fail-fast if the deque is modified during iteration. 3. The document describes common ArrayDeque methods like add(), addFirst(), clear(), clone(), and their usage through examples.

Uploaded by

Shubham manjhi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 79

Java Collection (java.util.

class)
By Shubham Manjhi

B.tech (2016-2020 in IIIT-Delhi)

Content :
\
ArrayDeque in Java

ArrayDeque in Java provides a way to apply resizable-array in addition to the implementation


of the Deque interface. It is also known as Array Double Ended Queue or Array Deck. This is a special
kind of array that grows and allows users to add or remove an element from both the sides of the queue.
Few important features of ArrayDeque are as follows:

 Array deques have no capacity restrictions and they grow as necessary to support usage.
 They are not thread-safe which means that in the absence of external synchronization,
ArrayDeque does not support concurrent access by multiple threads.
 Null elements are prohibited in the ArrayDeque.
 ArrayDeque class is likely to be faster than Stack when used as a stack.
 ArrayDeque class is likely to be faster than LinkedList when used as a queue

Declaration:
public class ArrayDeque Element
extends AbstractCollection
implements DequeElement, Cloneable, Serializable

Here, Element refers to the element which can refer to any class, such as Integer or String class.

Application :

1.) Resizable-array implementation of the Deque interface. Array


deques have no capacity restrictions; they grow as necessary to
support usage. They are not thread-safe; in the absence of external
synchronization, they do not support concurrent access by multiple
threads. Null elements are prohibited.
2.) This class is likely to be faster than Stack when used as a stack, and
faster than LinkedList when used as a queue.
3.) Most ArrayDeque operations run in amortized constant time.

Exceptions
include remove, removeFirstOccurrence, removeLastOccurrence, conta
ins, iterator.remove(), and the bulk operations, all of which run in linear
time.

DrawBack :
The iterators returned by this class's iterator method are fail-fast : If the deque is
modified at any time after the iterator is created, in any way except through the
iterator's own remove method, the iterator will generally throw
a ConcurrentModificationException. Thus, in the face of concurrent modification, the
iterator fails quickly and cleanly, rather than risking arbitrary, non -deterministic
behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally
speaking, impossible to make any hard guarantees in the presence of unsynchronized
concurrent modification. Fail-fast iterators throw ConcurrentModificationException on
a best-effort basis. Therefore, it would be wrong to write a program that depended on
this exception for its correctness: the fail-fast behavior of iterators should
be used only to detect bugs.
Java ArrayDeque Class: add() Method
Or

Java ArrayDeque Class: offer()Method

The add() method is used to insert an given element at the end of this deque.
public Boolean add(E e)
{
Add to last of queue;
}

Note: This method is equivalent to addLast(E).

Package: java.util
Java Platform: Java SE 8
Syntax: add(E e) .
Parameters: e = The element to add.
Return Value: true (as specified by Collection.add(E))
Return Value Type: Boolean
NullPointerException - if the specified element is nullThrows:
Example: Java ArrayDeque Class: add() Method
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
// Create an empty array deque with an initial capacity 5
Deque<Integer> deque = new ArrayDeque<Integer>(5);

// Use add() method to add 7 elements in the deque


deque.add(10);
deque.add(20);
deque.add(30);
deque.add(40);
deque.add(50);
deque.add(60);
deque.add(70);

// Print all the elements of deque


for (Integer n : deque) {
System.out.println(n);
}
}
}
Copy
Output:
10
20
30
40
50
60
70

Java ArrayDeque Class: addFirst() Method


Or

Java ArrayDeque Class: offerFirst() Method

The addFirst() method is used to insert an given element at the front of this
deque.
public Boolean addFirst(E e)
{
Add to First position of dequeue;
}

Package: java.util
Java Platform: Java SE 8
Syntax: addFirst(E e)
Parameters: e = The element to add.
Return Value Type: void for addFirst() and Boolean for offerFirst().
Throws: NullPointerException - if the specified element is null.

Example: Java ArrayDeque Class: addFirst() Method


import java.util.ArrayDeque;
import java.util.Deque;

public class Main {


public static void main(String[] args) {

// Create an empty array deque with an initial capacity 3


Deque<Integer> deque = new ArrayDeque<Integer>(3);

// Use add() method to add elements in the deque


deque.add(40);
deque.add(50);
deque.add(60);

// Use addFirst() method to add 3 elements


// at the front of the deque and print all the elements
deque.addFirst(30);
for (Integer number : deque) {
System.out.println("Number = " + number);
}
deque.addFirst(20);
System.out.println();
for (Integer number : deque) {
System.out.println("Number = " + number);
}
deque.addFirst(10);
System.out.println();
for (Integer number : deque) {
System.out.println("Number = " + number);
}
}
}
Copy
Output:

Number = 30,Number = 40,Number = 50,Number = 60,Number = 20,


Number = 30,Number = 40,Number = 50,Number = 60,Number = 10,
Number = 20,Number = 30,Number = 40,Number = 50,Number = 60

Java ArrayDeque Class: addLast()Method


Or

Java ArrayDeque Class: offerLast()Method

The addLast() method is used to insert a given element at the end of this
deque.

Note: This method is equivalent to add(E).


Package: java.util

Java Platform: Java SE 8

Syntax: addLast(E e)

Parameters: e = The element to add.

Return Value Type: void for addLast() and Boolean for offerLast()

Throws: NullPointerException - if the specified element is null

import java.util.ArrayDeque;
import java.util.Deque;

public class Main {


public static void main(String[] args) {

// Create an empty array deque with an initial capacity 3


Deque<Integer> deque = new ArrayDeque<Integer>(3);

// Use add() method to add elements in the deque


deque.add(10);
deque.add(20);
deque.add(30);

// Use addLast() method to add 3 elements


// at the last of the deque and print all the elements
deque.addLast(40);
for (Integer n : deque) {
System.out.println("Number = " + n);
}
deque.addLast(50);
System.out.println();
for (Integer n : deque) {
System.out.println("Number = " + n);
}
deque.addLast(60);
System.out.println();
for (Integer n : deque) {
System.out.println("Number = " + n);
}
}
}

Output:
Number = 10,Number = 20,Number = 30,Number = 40,Number = 10,
Number = 20,Number = 30,Number = 40,Number = 50,Number = 10,
Number = 20,Number = 30,Number = 40,Number = 50,Number = 60

Java ArrayDeque Class: clear() Method


The clear() method is used to removes all of the elements from a given deque.
public void clear()

{
Clear the dequeu.

Package: java.util
Java Platform: Java SE 8
Syntax: clear()
Return Value Type: void

Example: Java ArrayDeque Class: clear() Method


import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
// create an empty array deque with an initial capacity
Deque<Integer> deque = new ArrayDeque<Integer>(8);
// use add() method to add elements in the deque
deque.add(10);
deque.add(20);
deque.add(30);
// print all the elements available in deque
for (Integer n : deque) {
System.out.println("Number = " + n);
}
// Let clear all the elements in the deque
deque.clear();
// print all the elements available in deque
System.out.println("After clearing all the elements in the deque:");
for (Integer n : deque) {
System.out.println("Number = " + n);
}
}
}

Output:
Number = 10
Number = 20
Number = 30
After clearing all the elements in the deque:
Java ArrayDeque Class: clone() Method

public ArrayDeque<E> clone()

The clone() method is used to create copy of a given deque.

Package: java.util

Java Platform: Java SE 8

Syntax:
clone()
Return Value:

a copy of this deque

Return Value Type: ArrayDeque<E - the type of elements held in this


collection>

Pictorial Presentation
Example: Java ArrayDeque Class: clone() Method
import java.util.ArrayDeque;

import java.util.Deque;

public class Main {

public static void main(String[] args) {

// Create an empty array deque with an initial capacity

ArrayDeque<Integer> deque = new ArrayDeque<Integer>(5);

// Use add() method to add elements in the deque

deque.add(10);

deque.add(20);

deque.add(30);

deque.add(40);
System.out.println("Original deque:");

for (Integer n : deque) {

System.out.println("Number = " + n);

// clone the above deque,

Deque<Integer> cdeque = deque.clone();

// Print the elements of the clone deque

System.out.println("Coloned deque:");

for (Integer n : cdeque) {

System.out.println("Number = " + n);

Copy

Output:
Original deque:
Number = 10
Number = 20
Number = 30
Number = 40
Coloned deque:
Number = 10
Number = 20
Number = 30
Number = 40
Java ArrayDeque Class: contains() Method

public boolean contains(Object o)

The contains() method is used to check if a given deque contains an specified


element or not.

More formally, returns true if and only if this deque contains at least one
element e such that o.equals(e).

Package: java.util

Java Platform: Java SE 8

Syntax:
contains(Object o)
Parameters:

Name Description

o object to be checked for containment in this deque

Return Value:

true if this deque contains the specified element

Return Value Type: boolean

Pictorial Presentation
Example: Java ArrayDeque Class: contains() Method
import java.util.ArrayDeque;

import java.util.Deque;

public class Main {

public static void main(String[] args) {

// ArrayList with Capacity 4

ArrayDeque<String> StudentList = new ArrayDeque<String>(4);


//Added 4 elements

StudentList.add("David");

StudentList.add("Tom");

StudentList.add("Rohit");

StudentList.add("Paul");

System.out.println("Students in the list are : ");

System.out.println(StudentList);

System.out.print("Is list contains the student Tom?");

System.out.println(StudentList.contains("Tom"));

System.out.print("Is list contains the student Sudhir?");

System.out.println(StudentList.contains("Sudhir"));

Copy

Output:
Students in the list are :
[David, Tom, Rohit, Paul]
Is list contains the student Tom?true
Is list contains the student Sudhir?false
Java ArrayDeque Class: descendingIterator()
Method

public Iterator<E> descendingIterator()

The descendingIterator() method is used to iterator over the elements in a


given deque in reverse sequential order. The elements return in order from
last (tail) to first (head).

Package: java.util

Java Platform: Java SE 8

Syntax:
descendingIterator()
Return Value:

An iterator over the elements in this deque in reverse sequence

Return Value Type: Iterator<E - the type of elements held in this collection>

Pictorial Presentation
Example: Java ArrayDeque Class: descendingIterator() Method
import java.util.ArrayDeque;

import java.util.Deque;

import java.util.Iterator;

public class Main {

public static void main(String[] args) {

Deque<Integer> deque = new ArrayDeque<Integer>(8);

// use add() method to add elements in the deque

deque.add(10);

deque.add(20);
deque.add(30);

deque.add(40);

System.out.println("Print all the elements of the original deque:");

for(Iterator itr = deque.iterator(); itr.hasNext();) {

System.out.println(itr.next());

System.out.println("Print all the elements of the original deque in reverse


order:");

for(Iterator desc_itrr = deque.descendingIterator();desc_itrr.hasNext();) {

System.out.println(desc_itrr.next());

Copy

Output:
Print all the elements of the original deque:
10
20
30
40
Print all the elements of the original deque in reverse order:
40
30
20
10
Java ArrayDeque Class: element() or peek()
Method

public E element()

The element() method is used to retrieve the head of the queue represented
by this deque. This method differs from peek only in that it throws an
exception if this deque is empty.

Note: This method is equivalent to getFirst().

Package: java.util

Java Platform: Java SE 8

Syntax:
element()
Return Value:

the head of the queue represented by this deque

Return Value Type: E - the type of elements held in this collection

Throws:

NoSuchElementException - if this deque is empty

Pictorial Presentation
Example: Java ArrayDeque Class: element() Method
import java.util.ArrayDeque;

import java.util.Deque;

import java.util.Iterator;

public class Main {

public static void main(String[] args) {

// Create an empty array deque with an initial capacity

ArrayDeque<Integer> deque = new ArrayDeque<Integer>(8);

// Use add() method to add elements in the deque

deque.add(10);

deque.add(20);

deque.add(30);

deque.add(40);
// Print all the elements of the original deque

System.out.println("Original elements of the deque: ");

for (Integer n : deque) {

System.out.println(n);

// Retrieve the first element of the deque.

int e = deque.element();

System.out.println("Retrieved element: " + e);

Copy

Output:
Original elements of the deque:
10
20
30
40
Retrieved element: 10
Java ArrayDeque Class: getFirst() or peekFirst
Method

public E getFirst()

The getFirst() method is used to retrieve the first element of a given deque.

This method differs from peekFirst only in that it throws an exception if this
deque is empty.

Package: java.util

Java Platform: Java SE 8

Syntax:
getFirst()
Return Value:

the head of this deque

Return Value Type: E - the type of elements held in this collection

Throws:

NoSuchElementException - if this deque is empty

Pictorial Presentation
Example: Java ArrayDeque Class: getFirst() Method
import java.util.ArrayDeque;

import java.util.Deque;

public class Main {

public static void main(String[] args) {

// Create an empty array deque with an initial capacity

Deque<Integer> deque = new ArrayDeque(8);

// Use add() method to add elements in the deque

deque.add(10);

deque.add(20);

deque.add(30);

deque.add(40);

// Print all the elements of the original deque


System.out.println("Original elements of the deque: ");

for (Integer n : deque) {

System.out.println(n);

// Retrieve the first element of the deque.

int e = deque.getFirst();

System.out.println("Retrieve the first element: " + e);

Copy

Output:
Powered by
Original elements of the deque:
10
20
30
40
Retrieve the first element: 10
Java ArrayDeque Class: getLast() or peekLast()
Method

public E getLast()

The getLast() method is used to retrieve the last element of a given deque.

This method differs from peekLast only in that it throws an exception if this
deque is empty.

Package: java.util

Java Platform: Java SE 8

Syntax:
getLast()
Return Value:

the tail of this deque

Return Value Type: E - the type of elements held in this collection

Throws:

NoSuchElementException - if this deque is empty

Pictorial Presentation
Example: Java ArrayDeque Class: getLast() Method
import java.util.ArrayDeque;

import java.util.Deque;

public class Main {

public static void main(String[] args) {

// Create an empty array deque with an initial capacity.

Deque<Integer> deque = new ArrayDeque(8);

// Use add() method to add elements in the deque

deque.add(10);

deque.add(20);

deque.add(30);

deque.add(40);

// Print all the elements of the original deque.


System.out.println("Original elements of the deque: ");

for (Integer n : deque) {

System.out.println(n);

// Retrieve the first element of the deque.

int e = deque.getLast();

System.out.println("Retrieve the last element: " + e);

Copy

Output:
Original elements of the deque:
10
20
30
40
Retrieve the last element: 40
Java ArrayDeque Class: isEmpty() Method

public boolean isEmpty()

Returns true if this deque contains no elements.

Package: java.util

Java Platform: Java SE 8

Syntax:
isEmpty()
Return Value:

true if this deque contains no elements

Return Value Type:boolean

Pictorial Presentation:
Example: Java ArrayDeque Class: isEmpty() Method
import java.util.ArrayDeque;

import java.util.Deque;

public class Main {

public static void main(String[] args) {

// Create an empty array deque with an initial capacity.


Deque<Integer> deque = new ArrayDeque(8);

// Test whether the Deque is empty or not.

if (deque.isEmpty())

System.out.println("The ArrayDeque is empty.");

else

System.out.println("The ArrayDeque is not empty.");

Copy

Output:
The ArrayDeque is empty.
Java ArrayDeque Class: iterator() Method

public Iterator<E> iterator()

Returns an iterator over the elements in this deque.

The elements will be ordered from first (head) to last (tail).

Package: java.util

Java Platform: Java SE 8

Syntax:
iterator()
Return Value:

an iterator over the elements in this deque

Return Value Type:Iterator<E - the type of elements held in this collection>

Pictorial Presentation
Example: Java ArrayDeque Class: iterator() Method
import java.util.ArrayDeque;

import java.util.Deque;

import java.util.Iterator;

public class Main {

public static void main(String[] args) {

// Create an empty array deque with an initial capacity

Deque<Integer> deque = new ArrayDeque<Integer>(8);

// Use add() method to add elements in the deque

deque.add(10);

deque.add(20);

deque.add(30);

deque.add(25);

// Print all the elements of the original deque.

System.out.println("Original elements of the deque: ");

for (Integer n : deque) {

System.out.println(n);

// iterator() is used to print all the elements

System.out.println("Print all the elements using iterator:");

for(Iterator itr = deque.iterator();itr.hasNext();) {

System.out.println(itr.next());

}
}

Copy

Output:
Original elements of the deque:
10
20
30
25
Print all the elements using iterator:
10
20
30
25
Java ArrayDeque Class: poll() Method

public E poll()

The poll() method is used to retrieve and remove the head of the queue
represented by a given deque (in other words, the first element of this deque).

This method is equivalent to pollFirst().

Package: java.util

Java Platform: Java SE 8

Syntax:
poll()
Return Value:

the head of the queue represented by this deque, or null if this deque is empty

Return Value Type: E - the type of elements held in this collection

Pictorial Presentation
Example: Java ArrayDeque Class: poll() Method
import java.util.ArrayDeque;

import java.util.Deque;

public class Main {

public static void main(String[] args) {

// Create an array deque

Deque<Integer> deque = new ArrayDeque<Integer>(8);

// use add() method to add elements in the deque


deque.add(100);

deque.add(200);

deque.add(150);

deque.add(95);

// Print all the elements of the original deque

System.out.println("Elements of the original deque:");

for (Integer number : deque) {

System.out.println("Number = " + number);

int retval = deque.poll();

System.out.println("Removed element: " + retval);

// printing all the elements available in deque after using poll()

for (Integer number : deque) {

System.out.println("Number = " + number);

Copy

Output:
Powered by
Elements of the original deque:
Number = 100
Number = 200
Number = 150
Number = 95
Removed element: 100
Number = 200
Number = 150
Number = 95
Java ArrayDeque Class: pollFirst() or
removeFirst() or poll Method

public E pollFirst()

The pollFirst() method is used to retrieve and remove the first element of a
given deque.

Package: java.util

Java Platform: Java SE 8

Syntax:
pollFirst()
Return Value:

the head of this deque, or null if this deque is empty

Return Value Type: E - the type of elements held in this collection

Pictorial Presentation
Example: Java ArrayDeque Class: pollFirst() Method
import java.util.ArrayDeque;

import java.util.Deque;

public class Main {

public static void main(String[] args) {

// Create an array deque

Deque<Integer> deque = new ArrayDeque<Integer>(8);


// use add() method to add elements in the deque

deque.add(100);

deque.add(200);

deque.add(150);

deque.add(95);

// Print all the elements of the original deque

System.out.println("Elements of the original deque:");

for (Integer number : deque) {

System.out.println("Number = " + number);

int retval = deque.pollFirst();

System.out.println("Removed element: " + retval);

// printing all the elements available in deque after using pollFirst()

for (Integer number : deque) {

System.out.println("Number = " + number);

Copy

Output:
Elements of the original deque:
Number = 100
Number = 200
Number = 150
Number = 95
Removed element: 100
Number = 200
Number = 150
Number = 95
Java ArrayDeque Class: pollLast() or removeLast()
Method

public E pollLast()

The pollLast() method is used to retrieve and remove the last element of a
given deque, or returns null if this deque is empty.

Package: java.util

Java Platform: Java SE 8

Syntax:
pollLast()
Return Value:

the tail of this deque, or null if this deque is empty

Return Value Type: E - the type of elements held in this collection

Pictorial Presentation
Example: Java ArrayDeque Class: pollLast() Method
import java.util.ArrayDeque;

import java.util.Deque;

public class Main {

public static void main(String[] args) {

// Create an array deque

Deque<Integer> deque = new ArrayDeque<Integer>(8);

// use add() method to add elements in the deque

deque.add(100);

deque.add(200);
deque.add(150);

deque.add(95);

// Print all the elements of the original deque

System.out.println("Elements of the original deque:");

for (Integer number : deque) {

System.out.println("Number = " + number);

int retval = deque.pollLast();

System.out.println("Removed element: " + retval);

// printing all the elements available in deque after using pollLast()

for (Integer number : deque) {

System.out.println("Number = " + number);

Copy

Output:
Elements of the original deque:
Number = 100
Number = 200
Number = 150
Number = 95
Removed element: 95
Number = 100
Number = 200
Number = 150
Java ArrayDeque Class: removeFirstOccurrence()
Method

public boolean removeFirstOccurrence(Object o)

The removeFirstOccurrence() method is used to remove the first occurrence


of an specified element in a given deque (when traversing the deque from
head to tail). If the deque does not contain the element, it is unchanged. More
formally, removes the first element e such that o.equals(e) (if such an element
exists).

Package: java.util

Java Platform: Java SE 8

Syntax:
removeFirstOccurrence(Object o)
Parameters:

Name Description

o element to be removed from this deque, if present

Return Value:

true if the deque contained the specified element

Return Value Type: boolean

Pictorial Presentation
Example: Java ArrayDeque Class: removeFirstOccurrence() Method
import java.util.ArrayDeque;

import java.util.Deque;

public class Main {

public static void main(String[] args) {

// Create an array deque

Deque<Integer> deque = new ArrayDeque<Integer>(8);

// Use add() method to add elements in the deque

deque.add(100);
deque.add(200);

deque.add(150);

deque.add(95);

deque.add(200);

// Print all the elements of the original deque

System.out.println("Elements of the original deque:");

for (Integer number : deque) {

System.out.println("Number = " + number);

// removeFirstOccurrence() will remove first occurrence of element 200

deque.removeFirstOccurrence(200);

// Print all the elements available in deque

System.out.println("New deque:");

for (Integer number : deque) {

System.out.println("Number = " + number);

Copy

Output:
Elements of the original deque:
Number = 100
Number = 200
Number = 150
Number = 95
Number = 200
New deque:
Number = 100
Number = 150
Number = 95
Number = 200
Java ArrayDeque Class: removeLastOccurrence()
Method

public boolean removeLastOccurrence(Object o)

The removeLastOccurrence() method is used to remove the last occurrence of


the specified element in this deque (when traversing the deque from head to
tail).

If the deque does not contain the element, it is unchanged. More formally,
removes the last element e such that o.equals(e) (if such an element exists).

Package: java.util

Java Platform: Java SE 8

Syntax:
removeLastOccurrence(Object o)
Parameters:

Name Description

o element to be removed from this deque, if present

Return Value:

true if the deque contained the specified element

Return Value Type: boolean

Pictorial Presentation
Example: Java ArrayDeque Class: removeLastOccurrence() Method
import java.util.ArrayDeque;

import java.util.Deque;

public class Main {

public static void main(String[] args) {

// Create an array deque

Deque<Integer> deque = new ArrayDeque<Integer>(8);

// Use add() method to add elements in the deque

deque.add(100);
deque.add(200);

deque.add(150);

deque.add(95);

deque.add(200);

// Print all the elements of the original deque

System.out.println("Elements of the original deque:");

for (Integer number : deque) {

System.out.println("Number = " + number);

// removeLastOccurrence() will remove last occurrence of element 200

deque.removeLastOccurrence(200);

// Print all the elements available in deque

System.out.println("New deque:");

for (Integer number : deque) {

System.out.println("Number = " + number);

Copy

Output:
Elements of the original deque:
Number = 100
Number = 200
Number = 150
Number = 95
Number = 200
New deque:
Number = 100
Number = 200
Number = 150
Number = 95

Java ArrayDeque Class: size() Method

public int size()

The size() method is used to count the number of elements in a given deque.

Package: java.util

Java Platform: Java SE 8

Syntax:
size()
Return Value:

the number of elements in this deque

Return Value Type: int

Pictorial Presentation
Example: Java ArrayDeque Class: size() Method
import java.util.ArrayDeque;

import java.util.Deque;

public class Main {

public static void main(String[] args) {

// Create an array deque

Deque<Integer> deque = new ArrayDeque<Integer>(8);

// Use add() method to add elements in the deque

deque.add(100);

deque.add(200);

deque.add(150);

deque.add(95);

deque.add(200);

// Print all the elements of the original deque

System.out.println("Elements of the original deque:");

for (Integer number : deque) {

System.out.println("Number = " + number);

// size() will print the size of this deque

int deque_size = deque.size();

System.out.println("Size of deque = " + deque_size);

Copy
Output:
Elements of the original deque:
Number = 100
Number = 200
Number = 150
Number = 95
Number = 200
Size of deque = 5
Commented [SM1]: import java.util.Arrays;
Java.util.Arrays Class
public class ArrayDemo {
Class methods public static void main(String[] args) {

// initializing unsorted byte array


Sr.No. Method & Description byte byteArr[] = {10,20,15,22,35};

// sorting array
Arrays.sort(byteArr);
1 static <T> List<T> asList(T... a)
// let us print all the elements
available in list
How to use it : List list1 = Arrays.asList(a); System.out.println("The sorted byte
array is:");

Return Value: This method returns a list view of


for (byte number : byteArr) {
System.out.println("Number = " +
number);
the specified array. Simply converting array to list. }

This method returns a fixed-size list backed by the specified array. // entering the value to be searched
byte searchVal = 35;

2 static int binarySearch(byte[] a, byte key) int retVal =


Arrays.binarySearch(byteArr,searchVal);

This method searches the specified array of bytes for the specified value System.out.println("The index of
element 35 is : " + retVal);
using the binary search algorithm. }
}
3 static int binarySearch(byte[] a, int fromIndex, int toIndex, byte
key)
Commented [SM2]: import java.util.Arrays;

This method searches a range of the specified array of bytes for the public class ArrayDemo {
public static void main(String[] args) {
specified value using the binary search algorithm.
// initializing unsorted byte array
byte byteArr[] = {10,20,15,22,35};
4 static int binarySearch(char[] a, char key)
// sorting array
This method searches the specified array of chars for the specified value Arrays.sort(byteArr);

using the binary search algorithm. // let us print all the elements
available in list
System.out.println("The sorted byte
5 static int binarySearch(char[] a, int fromIndex, int toIndex, char array is:");
key) for (byte number : byteArr) {
System.out.println("Number = " +
number);
This method searches a range of the specified array of chars for the }
specified value using the binary search algorithm. // entering the value to be searched
byte searchVal = 35;

6 static int binarySearch(double[] a, double key) int retVal =


Arrays.binarySearch(byteArr,searchVal);
This method searches the specified array of doubles for the specified value
System.out.println("The index of
using the binary search algorithm. element 35 is : " + retVal);
}
}
7 static int binarySearch(double[] a, int fromIndex, int toIndex,
double key)

This method searches a range of the specified array of doubles for the
specified value using the binary search algorithm.

8 static int binarySearch(float[] a, float key)

This method searches the specified array of floats for the specified value
using the binary search algorithm.

9 static int binarySearch(float[] a, int fromIndex, int toIndex, float


key)

This method searches a range of the specified array of floats for the
specified value using the binary search algorithm.

10 static int binarySearch(int[] a, int key)

This method searches the specified array of ints for the specified value
using the binary search algorithm.

11 static int binarySearch(int[] a, int fromIndex, int toIndex, int


key)

This method searches a range of the specified array of ints for the
specified value using the binary search algorithm.

12 static int binarySearch(long[] a, int fromIndex, int toIndex, long


key)

This method searches a range of the specified array of longs for the
specified value using the binary search algorithm.

13 static int binarySearch(long[] a, long key)

This method searches the specified array of longs for the specified value
using the binary search algorithm.

14 static int binarySearch(Object[] a, int fromIndex, int toIndex,


Object key)

This method searches a range of the specified array for the specified
object using the binary search algorithm.
15 static int binarySearch(Object[] a, Object key)

This method searches the specified array for the specified object using
the binary search algorithm.

16 static int binarySearch(short[] a, int fromIndex, int toIndex,


short key)

This method searches a range of the specified array of shorts for the
specified value using the binary search algorithm.

17 static int binarySearch(short[] a, short key)

This method searches the specified array of shorts for the specified value
using the binary search algorithm.

18 static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T


key, Comparator<? super T> c)

This method searches a range of the specified array for the specified
object using the binary search algorithm.

19 static <T> int binarySearch(T[] a, T key, Comparator<? super T>


c)

This method searches the specified array for the specified object using
the binary search algorithm.

20 static boolean[] copyOf(boolean[] original, int newLength)

This method copies the specified array, truncating or padding with false
(if necessary) so the copy has the specified length.

21 static byte[] copyOf(byte[] original, int newLength)

This method copies the specified array, truncating or padding with zeros
(if necessary) so the copy has the specified length.

22 static char[] copyOf(char[] original, int newLength)

This method copies the specified array, truncating or padding with null
characters (if necessary) so the copy has the specified length.
23 static double[] copyOf(double[] original, int newLength)

This method copies the specified array, truncating or padding with zeros
(if necessary) so the copy has the specified length.

24 static float[] copyOf(float[] original, int newLength)

This method copies the specified array, truncating or padding with zeros
(if necessary) so the copy has the specified length.

25 static int[] copyOf(int[] original, int newLength)

This method copies the specified array, truncating or padding with zeros
(if necessary) so the copy has the specified length.

26 static long[] copyOf(long[] original, int newLength)

This method copies the specified array, truncating or padding with zeros
(if necessary) so the copy has the specified length.

27 static short[] copyOf(short[] original, int newLength)

This method copies the specified array, truncating or padding with zeros
(if necessary) so the copy has the specified length.

28 static <T> T[] copyOf(T[] original, int newLength)

This method copies the specified array, truncating or padding with nulls
(if necessary) so the copy has the specified length.

29 static <T,U> T[] copyOf(U[] original, int newLength, Class<?


extends T[]> newType)

This method copies the specified array, truncating or padding with nulls
(if necessary) so the copy has the specified length.

30 static boolean[] copyOfRange(boolean[] original, int from, int to)

This method copies the specified range of the specified array into a new
array.

31 static byte[] copyOfRange(byte[] original, int from, int to)


This method copies the specified range of the specified array into a new
array.

32 static char[] copyOfRange(char[] original, int from, int to)

This method copies the specified range of the specified array into a new
array.

33 static double[] copyOfRange(double[] original, int from, int to)

This method copies the specified range of the specified array into a new
array.

34 static float[] copyOfRange(float[] original, int from, int to)

This method copies the specified range of the specified array into a new
array.

35 static int[] copyOfRange(int[] original, int from, int to)

This method copies the specified range of the specified array into a new
array.

36 static long[] copyOfRange(long[] original, int from, int to)

This method copies the specified range of the specified array into a new
array.

37 static short[] copyOfRange(short[] original, int from, int to)

This method copies the specified range of the specified array into a new
array.

38 static <T> T[] copyOfRange(T[] original, int from, int to)

This method copies the specified range of the specified array into a new
array.

39 static <T,U> T[] copyOfRange(U[] original, int from, int to,


Class<? extends T[]> newType)

This method copies the specified range of the specified array into a new
array.
40 static boolean deepEquals(Object[] a1, Object[] a2)

This method returns true if the two specified arrays are deeply equal to
one another.

41 static int deepHashCode(Object[] a)

This method returns a hash code based on the "deep contents" of the
specified array.

42 static String deepToString(Object[] a)

This method returns a string representation of the "deep contents" of the


specified array.

43 static boolean equals(boolean[] a, boolean[] a2)

This method returns true if the two specified arrays of booleans are equal
to one another.

44 static boolean equals(byte[] a, byte[] a2)

This method returns true if the two specified arrays of bytes are equal to
one another.

45 static boolean equals(char[] a, char[] a2)

This method returns true if the two specified arrays of chars are equal to
one another.

46 static boolean equals(double[] a, double[] a2)

This method returns true if the two specified arrays of doubles are equal
to one another.

47 static boolean equals(float[] a, float[] a2)

This method returns true if the two specified arrays of floats are equal to
one another.

48 static boolean equals(int[] a, int[] a2)


This method returns true if the two specified arrays of ints are equal to
one another.

49 static boolean equals(long[] a, long[] a2)

This method returns true if the two specified arrays of longs are equal to
one another.

50 static boolean equals(Object[] a, Object[] a2)

This method returns true if the two specified arrays of Objects are equal
to one another.

51 static boolean equals(short[] a, short[] a2)

This method returns true if the two specified arrays of shorts are equal to
one another.

52 static void fill(boolean[] a, boolean val)

This method assigns the specified boolean value to each element of the
specified array of booleans.

53 static void fill(boolean[] a, int fromIndex, int toIndex, boolean


val)

This method assigns the specified boolean value to each element of the
specified range of the specified array of booleans.

54 static void fill(byte[] a, byte val)

This method assigns the specified byte value to each element of the
specified array of bytes.

55 static void fill(byte[] a, int fromIndex, int toIndex, byte val)

This method assigns the specified byte value to each element of the
specified range of the specified array of bytes.

56 static void fill(char[] a, char val)

This method assigns the specified char value to each element of the
specified array of chars.
57 static void fill(char[] a, int fromIndex, int toIndex, char val)

This method assigns the specified char value to each element of the
specified range of the specified array of chars.

58 static void fill(double[] a, double val)

This method assigns the specified double value to each element of the
specified array of doubles.

59 static void fill(double[] a, int fromIndex, int toIndex, double val)

This method assigns the specified double value to each element of the
specified range of the specified array of doubles.

60 static void fill(float[] a, float val)

This method assigns the specified float value to each element of the
specified array of floats.

61 static void fill(float[] a, int fromIndex, int toIndex, float val)

This method assigns the specified float value to each element of the
specified range of the specified array of floats.

62 static void fill(int[] a, int val)

This method assigns the specified int value to each element of the
specified array of ints.

63 static void fill(int[] a, int fromIndex, int toIndex, int val)

This method assigns the specified int value to each element of the
specified range of the specified array of ints.

64 static void fill(long[] a, int fromIndex, int toIndex, long val)

This method assigns the specified long value to each element of the
specified range of the specified array of longs.

65 static void fill(long[] a, long val)


This method assigns the specified long value to each element of the
specified array of longs.

66 static void fill(Object[] a, int fromIndex, int toIndex, Object val)

This method assigns the specified Object reference to each element of the
specified range of the specified array of Objects.

67 static void fill(Object[] a, Object val)

This method assigns the specified Object reference to each element of the
specified array of Objects.

68 static void fill(short[] a, int fromIndex, int toIndex, short val)

This method assigns the specified short value to each element of the
specified range of the specified array of shorts.

69 static void fill(short[] a, short val)

This method assigns the specified short value to each element of the
specified array of shorts.

70 static int hashCode(boolean[] a)

This method returns a hash code based on the contents of the specified
array.

71 static int hashCode(byte[] a)

This method returns a hash code based on the contents of the specified
array.

72 static int hashCode(char[] a)

This method returns a hash code based on the contents of the specified
array.

73 static int hashCode(double[] a)

This method returns a hash code based on the contents of the specified
array.
74 static int hashCode(float[] a)

This method returns a hash code based on the contents of the specified
array.

75 static int hashCode(int[] a)

This method returns a hash code based on the contents of the specified
array.

76 static int hashCode(long[] a)

This method returns a hash code based on the contents of the specified
array.

77 static int hashCode(Object[] a)

This method returns a hash code based on the contents of the specified
array.

78 static int hashCode(short[] a)

This method returns a hash code based on the contents of the specified
array.

79 static void sort(byte[] a)

This method sorts the specified array of bytes into ascending numerical
order.

80 static void sort(byte[] a, int fromIndex, int toIndex)

This method sorts the specified range of the specified array of bytes into
ascending numerical order.

81 static void sort(char[] a)

This method sorts the specified array of chars into ascending numerical
order.

82 static void sort(char[] a, int fromIndex, int toIndex)


This method sorts the specified range of the specified array of chars into
ascending numerical order.

83 static void sort(double[] a)

This method sorts the specified array of doubles into ascending numerical
order.

84 static void sort(double[] a, int fromIndex, int toIndex)

This method sorts the specified range of the specified array of doubles
into ascending numerical order.

85 static void sort(float[] a)

This method sorts the specified array of floats into ascending numerical
order.

86 static void sort(float[] a, int fromIndex, int toIndex)

This method sorts the specified range of the specified array of floats into
ascending numerical order.

87 static void sort(int[] a)

This method sorts the specified array of ints into ascending numerical
order.

88 static void sort(int[] a, int fromIndex, int toIndex)

This method sorts the specified range of the specified array of ints into
ascending numerical order.

89 static void sort(long[] a)

This method sorts the specified array of longs into ascending numerical
order.

90 static void sort(long[] a, int fromIndex, int toIndex)

This method sorts the specified range of the specified array of longs into
ascending numerical order.
91 static void sort(Object[] a)

This method sorts the specified array of objects into ascending order,
according to the natural ordering of its elements.

92 static void sort(Object[] a, int fromIndex, int toIndex)

This method sorts the specified range of the specified array of objects into
ascending order, according to the natural ordering of its elements.

93 static void sort(short[] a)

This method sorts the specified array of shorts into ascending numerical
order.

94 static void sort(short[] a, int fromIndex, int toIndex)

This method sorts the specified range of the specified array of shorts into
ascending numerical order.

95 static <T> void sort(T[] a, Comparator<? super T> c)

This method sorts the specified array of objects according to the order
induced by the specified comparator.

96 static <T> void sort(T[] a, int fromIndex, int toIndex,


Comparator<? super T> c)

This method sorts the specified range of the specified array of objects
according to the order induced by the specified comparator.

97 static String toString(boolean[] a)

This method returns a string representation of the contents of the


specified array of boolean.

98 static String toString(byte[] a)

This method returns a string representation of the contents of the


specified array of bytes.

99 static String toString(char[] a)


This method returns a string representation of the contents of the
specified array of chars.

100 static String toString(double[] a)

This method returns a string representation of the contents of the


specified array of doubles.

101 static String toString(float[] a)

This method returns a string representation of the contents of the


specified array of floats.

102 static String toString(int[] a)

This method returns a string representation of the contents of the


specified array of ints.

103 static String toString(long[] a)

This method returns a string representation of the contents of the


specified array of longs.

104 static String toString(Object[] a)

This method returns a string representation of the contents of the


specified array of ints.

105 static String toString(short[] a)

This method returns a string representation of the contents of the


specified array of shorts.
Java.util.Collections Class

Sr.No. Method & Description

1
java.util.Collections.addAll() Commented [SM3]: import java.util.*;

Description : This method adds all of the specified public class CollectionsDemo {
public static void main(String args[]) {

elements to the specified collection. // create array list object


List arrlist = new ArrayList();

Declaration : boolean b = Collections.addAll(arrlist, "1","2","3"); // populate the list


arrlist.add("A");
arrlist.add("B");
Or arrlist.add("C");

System.out.println("Initial
collection value: "+arrlist);

Parameters // add values to this collection


boolean b =
Collections.addAll(arrlist, "1","2","3");
 arrlist − This is the collection into which elements are to be inserted.
System.out.println("Final collection
 a − This is the elements to insert into c { "1","2","3" }. value: "+arrlist);
}

Return Value
}
Let us compile and run the above program, this
will produce the following result.
The method call returns 'true' if the collection changed as a result of the
Initial collection value: [A, B, C]
call Final collection value: [A, B, C, 1, 2, 3]

Exception
 UnsupportedOperationException − This is thrown if c does not support the
add method.

 NullPointerException − This is thrown if elements contains one or more null


values and c does not support null elements.

 IllegalArgumentException − This is thrown if some aspect of a value in


elements prevents it from being added to c.
2
java.util.Collections.asLifoQueue() Commented [SM4]: import java.util.*;

public class CollectionsDemo {


public static void main(String args[]) {
static <T> Queue<T> asLifoQueue(Deque<T> deque)
// create Deque object
Deque<Integer> deque = new
ArrayDeque<Integer>(7);

// populate the object

Description : This method returns a view of a Deque as a Last-in-


deque.add(1);
deque.add(2);
deque.add(3);
first-out (Lifo) Queue. Simply it convert dequeue into deque.add(4);
deque.add(5);
queue. deque.add(6);
deque.add(7);

Declaration : Queue nq = Collections.asLifoQueue(deque);


// get queue from the deque
Queue nq =
Collections.asLifoQueue(deque);

Parameters : deque − This is the deque. System.out.println("View of the queue


is: "+nq);

Return Value : The method call returns the queue.


}
}
Let us compile and run the above program, this
Exception : NA. will produce the following result.
View of the queue is: [1, 2, 3, 4, 5, 6, 7]

3
java.util.Collections.binarySearch() Commented [SM5]: import java.util.*;

public class CollectionsDemo {


public static void main(String args[]) {
static <T> int binarySearch(List<? extends Comparable<? super T>> list, T
key) // create arraylist
ArrayList<String> arlst = new
ArrayList<String>();
Description : This method searches the specified list for the specified // populate the list
arlst.add("TP");
object using the binary search algorithm. arlst.add("PROVIDES");
arlst.add("QUALITY");

Declaration : int index = Collections.binarySearch(arlst, key);


arlst.add("TUTORIALS");

// search the list for key 'QUALITY'


int index =

Parameters Collections.binarySearch(arlst, "QUALITY");

System.out.println("'QUALITY' is
 list − This is the list to be searched. available at index: "+index);
}
 key − This is the key to be searched for. }
Return Value : The method call returns the index of the
search key, if it is contained in the list.
Exception : ClassCastException − This is thrown if the list
contains elements that are not mutually
comparable.

4
java.util.Collections.binarySearch()

static <T> int binarySearch(List<? extends T> list, T key, Comparator<?


super T< c)

Description : This method searches the specified list for the specified
object using the binary search algorithm in specific range.

Declaration : int index = Collections.binarySearch(list, key, c);


Parameters
 list − This is the list to be searched.

 key − This is the key to be searched for.

 c − This is the comparator by which the list is ordered. A null value indicates
that the elements' natural ordering should be used.

Return Value
The method call returns the index of the search key, if it is contained in
the list.

Exception
ClassCastException − This is thrown if the list contains elements that
are not mutually comparable using the specified comparator.
5 static <E> Collection<E> checkedCollection(Collection<E> c, Class<E>
type)

This method returns a dynamically typesafe view of the specified collection.

6 static <E> List<E> checkedList(List<E> list, Class<E> type)

This method returns a dynamically typesafe view of the specified list.

7 static <K,V> Map<K,V> checkedMap(Map<K,V> m, Class<K> keyType,


Class<V> valueType)

This method returns a dynamically typesafe view of the specified map.

8 static <E> Set<E> checkedSet(Set<E> s, Class<E> type)

This method returns a dynamically typesafe view of the specified set.

9 static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K,V> m,


Class<K> keyType, Class<V> valueType)

This method returns a dynamically typesafe view of the specified sorted map.

10 static <E> SortedSet<E>checkedSortedSet(SortedSet<E> s, Class<E>


type)

This method returns a dynamically typesafe view of the specified sorted set.

11 static <T> void copy(List<? super T> dest, List<? extends T> src)

This method copies all of the elements from one list into another.

12 static boolean disjoint(Collection<?> c1, Collection<?> c2)

This method returns true if the two specified collections have no elements in
common.

13 static <T> List<T> emptyList()


This method returns the empty list (immutable).

14 static <K,V> Map<K,V> emptyMap()

This method returns the empty map (immutable).

15 static <T> Set<T> emptySet()

This method returns the empty set (immutable).

16 static <T> Enumeration<T> enumeration(Collection<T> c)

This method returns an enumeration over the specified collection.

17 static <T> void fill(List<? super T> list, T obj)

This method replaces all of the elements of the specified list with the specified
element.

18 static int frequency(Collection<?> c, Object o)

This method returns the number of elements in the specified collection equal to the
specified object.

19 static int indexOfSubList(List<?> source, List<?> target)

This method returns the starting position of the first occurrence of the specified
target list within the specified source list, or -1 if there is no such occurrence.

20 static int lastIndexOfSubList(List<?> source, List<?> target)

This method returns the starting position of the last occurrence of the specified target
list within the specified source list, or -1 if there is no such occurrence.

21 static <T> ArrayList<T> list(Enumeration<T> e)

This method returns an array list containing the elements returned by the specified
enumeration in the order they are returned by the enumeration.

22 static <T extends Object & Comparable<? super T> >T max(Collection<?
extends T> coll)
This method returns the maximum element of the given collection, according to the
natural ordering of its elements.

23 static <T> T max(Collection<? extends T> coll, Comparator<? super T>


comp)

This method returns the maximum element of the given collection, according to the
order induced by the specified comparator.

24 static <T extends Object & Comparable<? super T>>T min(Collection<?


extends T> coll)

This method Returns the minimum element of the given collection, according to the
natural ordering of its elements.

25 static <T> T min(Collection<? extends T> coll, Comparator<? super T>


comp)

This method returns the minimum element of the given collection, according to the
order induced by the specified comparator.

26 static <T> List<T> nCopies(int n, T o)

This method returns an immutable list consisting of n copies of the specified object.

27 static <E> Set<E> newSetFromMap(Map<E,Boolean> map)

This method returns a set backed by the specified map.

28 static <T> boolean replaceAll(List<T> list, T oldVal, T newVal)

This method replaces all occurrences of one specified value in a list with another.

29 static void reverse(List<?> list)

This method reverses the order of the elements in the specified list.

30 static <T> Comparator<T> reverseOrder()

This method returns a comparator that imposes the reverse of the natural ordering
on a collection of objects that implement the Comparable interface.

31 static <T> Comparator<T> reverseOrder(Comparator<T> cmp)


This method returns a comparator that imposes the reverse ordering of the specified
comparator.

32 static void rotate(List<?> list, int distance)

This method rotates the elements in the specified list by the specified distance.

33 static void shuffle(List<?> list)

This method randomly permutes the specified list using a default source of
randomness.

34 static void shuffle(List<?> list, Random rnd)

This method randomly permute the specified list using the specified source of
randomness.

35 static <T> Set<T> singleton(T o)

This method returns an immutable set containing only the specified object.

36 static <T> List<T> singletonList(T o)

This method returns an immutable list containing only the specified object.

37 static <K,V> Map<K,V> singletonMap(K key, V value)

This method returns an immutable map, mapping only the specified key to the
specified value.

38 static <T extends Comparable<? super T>> void sort(List<T> list)

This method sorts the specified list into ascending order, according to the natural
ordering of its elements.

39 static <T> void sort(List<T> list, Comparator<? super T> c)

This method sorts the specified list according to the order induced by the specified
comparator.

40 static void swap(List<?> list, int i, int j)

This method swaps the elements at the specified positions in the specified list.
41 static <T> Collection<T> synchronizedCollection(Collection<T> c)

This method returns a synchronized (thread-safe) collection backed by the specified


collection.

42 static <T> List<T> synchronizedList(List<T> list)

This method returns a synchronized (thread-safe) list backed by the specified list.

43 static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)

This method returns a synchronized (thread-safe) map backed by the specified map.

44 static <T> Set<T> synchronizedSet(Set<T> s)

This method returns a synchronized (thread-safe) set backed by the specified set.

45 static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V>


m)

This method returns a synchronized (thread-safe) sorted map backed by the


specified sorted map.

46 static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)

This method returns a synchronized (thread-safe) sorted set backed by the specified
sorted set.

47 static <T> Collection<T> unmodifiableCollection(Collection<? extends T>


c)

This method returns an unmodifiable view of the specified collection.

48 static <T> List<T> unmodifiableList(List<? extends T> list)

This method returns an unmodifiable view of the specified list.

49 static <K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V>


m)

This method returns an unmodifiable view of the specified map.

50 static <T> Set<T> unmodifiableSet(Set<? extends T> s)

This method returns an unmodifiable view of the specified set.


51 static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K,?
extends V> m)

This method returns an unmodifiable view of the specified sorted map.

52 static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)

This method returns an unmodifiable view of the specified sorted set.

You might also like