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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources