What is the Deque.clear() method in Java?

In this shot, we will discuss how to use the Deque.clear() method in Java.

The Deque.clear() method is present in the Deque interface inside the java.util package.

The Deque.clear() method is used to remove all the elements from the deque.

Syntax

void deque.clear()

Parametera

The Deque.clear() method doesn’t take any parameters.

Return value

The Deque.clear() method doesn’t return anything.

Code

Let us take a look at the code snippet below.

import java.util.*;
class Main
{
public static void main(String[] args)
{
Deque<Integer> d = new LinkedList<Integer>();
d.add(212);
d.add(23);
d.add(621);
d.add(1280);
d.add(3121);
d.add(18297);
d.add(791);
d.clear();
System.out.println("Elements in the deque are: "+d);
}
}

Explanation

  • In line 1: We import the required package.
  • In line 2: We make a Main class.
  • In line 4: We make a main function.
  • In line 6: We declare a deque that consists of Integer type elements.
  • In lines 8-14: We use the Deque.add() method to insert the elements in the deque.
  • In line 16: We use the clear() method to remove all the elements from the deque.
  • In line 17: We display the deque elements.

In this way, we can use the Deque.clear() method in Java.

Free Resources