Java LinkedHashSet size() Method

The LinkedHashSet.size() method in Java is used to get the number of elements present in a LinkedHashSet.

Table of Contents

  1. Introduction
  2. size Method Syntax
  3. Examples
    • Getting the Size of a LinkedHashSet
    • Handling Empty LinkedHashSet
  4. Conclusion

Introduction

The LinkedHashSet.size() method is a member of the LinkedHashSet class in Java. It allows you to retrieve the number of elements present in the LinkedHashSet.

size Method Syntax

The syntax for the size method is as follows:

public int size()
  • The method does not take any parameters.
  • The method returns an integer value representing the number of elements in the LinkedHashSet.

Examples

Getting the Size of a LinkedHashSet

The size method can be used to retrieve the number of elements in a LinkedHashSet.

Example

import java.util.LinkedHashSet;

public class SizeExample {
    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");

        // Getting the size of the LinkedHashSet
        int size = animals.size();

        // Printing the size
        System.out.println("Size of LinkedHashSet: " + size);
    }
}

Output:

Size of LinkedHashSet: 3

Handling Empty LinkedHashSet

If the LinkedHashSet is empty, the size method will return 0.

Example

import java.util.LinkedHashSet;

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

        // Getting the size of the empty LinkedHashSet
        int size = animals.size();

        // Printing the size
        System.out.println("Size of empty LinkedHashSet: " + size);
    }
}

Output:

Size of empty LinkedHashSet: 0

Conclusion

The LinkedHashSet.size() method in Java provides a way to retrieve the number of elements present in a LinkedHashSet. By understanding how to use this method, you can efficiently manage and track the size of your collections. The method ensures that you can obtain the count of elements, making it useful for various operations and validations in your Java applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top