This example shows how to get the size of the LinkedHashSet object in Java (LinkedHashSet length). This example also shows how to use the LinkedHashSet size method.
How to get the size of the LinkedHashSet using the size method?
The size
method of the LinkedHashSet class returns the number of elements currently stored in the LinkedHashSet object.
1 |
public int size() |
The size
method returns an int value representing the number of elements of the linked hash set object. It returns 0 if the set object is empty or does not contain any elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.LinkedHashSet; public class LinkedHashSetSizeExample { public static void main(String[] args) { LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<Integer>(); /* * To get the number of elements stored in * the LinekdHashSet object, use the size method. */ //this will return 0 as there are no elements System.out.println( linkedHashSet.size() ); //add an element linkedHashSet.add(1); //this will return 1 as there is one element in the set System.out.println( linkedHashSet.size() ); } } |
Output
1 2 |
0 1 |
How to check if LinkedHashSet is empty using the size method?
We can check if LinkedHashSet is empty using the size
method. In order to do that, we need to compare the output of the size
method with 0 as given below. If the return value of the size
method is 0 then the linked hash set is empty, otherwise not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.LinkedHashSet; public class LinkedHashSetSizeExample { public static void main(String[] args) { LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<Integer>(); //this will print true as there 0 elements in the set System.out.println( "Is empty? " + (linkedHashSet.size() == 0) ); //add some elements linkedHashSet.add(101); linkedHashSet.add(102); //this will return false as there are 2 elements System.out.println( "Is empty? " + (linkedHashSet.size() == 0) ); } } |
Output
1 2 |
Is empty? true Is empty? false |
This example is a part of the Java LinkedHashSet Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 LinkedHashSet