Size of HashSet
Its very important to know the size of HashSet as it is required in most of the times while coding
We have size() method in HashSet class which helps us to determine the size of HashSet
Size is the number of elements in that HashSet
public int size()
Example :
- import java.util.*;
- public class HashSetSize {
- public static void main(String[] args) {
- HashSet<Integer> hs = new HashSet<Integer>();
- hs.add(14);
- hs.add(7);
- hs.add(21);
- hs.add(28);
- hs.add(35);
- hs.add(42);
- System.out.println("Initial Size of HashSet: "+hs.size());
- hs.remove(35);
- hs.remove(42);
- System.out.println("Size after removing 2 elements: "+hs.size());
- System.out.println("Final HashSet after removal of 2 elements: ");
- for(int ele: hs){
- System.out.println(ele);
- }
- }
- }
import java.util.*; public class HashSetSize { public static void main(String[] args) { HashSet<Integer> hs = new HashSet<Integer>(); hs.add(14); hs.add(7); hs.add(21); hs.add(28); hs.add(35); hs.add(42); System.out.println("Initial Size of HashSet: "+hs.size()); hs.remove(35); hs.remove(42); System.out.println("Size after removing 2 elements: "+hs.size()); System.out.println("Final HashSet after removal of 2 elements: "); for(int ele: hs){ System.out.println(ele); } } }
Here Size just tells how many elements are present in the HashSet
Don’t get confuse size with capacity in the HashSet, we will talk about capacity separately
Just remember Size() returns number of elements present in HashSet
Remember size() is a method , not a variable in the HashSet class.