Java LinkedHashSet clear() Method

The LinkedHashSet.clear() method in Java is used to remove all elements from a LinkedHashSet.

Table of Contents

  1. Introduction
  2. clear Method Syntax
  3. Examples
    • Clearing Elements from a LinkedHashSet
    • Checking if the LinkedHashSet is Empty
  4. Conclusion

Introduction

The LinkedHashSet.clear() method is a member of the LinkedHashSet class in Java. It allows you to remove all elements from a LinkedHashSet, leaving it empty.

clear() Method Syntax

The syntax for the clear method is as follows:

public void clear()
  • The method does not take any parameters.
  • The method does not return any value.

Examples

Clearing Elements from a LinkedHashSet

The clear method can be used to remove all elements from a LinkedHashSet.

Example

import java.util.LinkedHashSet;

public class ClearExample {
    public static void main(String[] args) {
        // Creating a LinkedHashSet of Strings
        LinkedHashSet<String> animals = new LinkedHashSet<>();

        // Adding elements to the LinkedHashSet
        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Elephant");

        // Printing the LinkedHashSet
        System.out.println("LinkedHashSet before clear: " + animals);

        // Clearing all elements from the LinkedHashSet
        animals.clear();

        // Printing the LinkedHashSet after clear
        System.out.println("LinkedHashSet after clear: " + animals);
    }
}

Output:

LinkedHashSet before clear: [Lion, Tiger, Elephant]
LinkedHashSet after clear: []

Checking if the LinkedHashSet is Empty

After using the clear method, you can check if the LinkedHashSet is empty using the isEmpty method.

Example

import java.util.LinkedHashSet;

public class IsEmptyExample {
    public static void main(String[] args) {
        // Creating a LinkedHashSet of Strings
        LinkedHashSet<String> animals = new LinkedHashSet<>();

        // Adding elements to the LinkedHashSet
        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Elephant");

        // Clearing all elements from the LinkedHashSet
        animals.clear();

        // Checking if the LinkedHashSet is empty
        boolean isEmpty = animals.isEmpty();

        // Printing the result
        System.out.println("Is the LinkedHashSet empty? " + isEmpty);
    }
}

Output:

Is the LinkedHashSet empty? true

Conclusion

The LinkedHashSet.clear() method in Java provides a way to remove all elements from a LinkedHashSet. By understanding how to use this method, you can efficiently manage collections by resetting them to an empty state when necessary. The method ensures that the LinkedHashSet is emptied, allowing for reuse or reinitialization.

Comments