Friday, 18 April 2014

HashSet : size : get the Number of Elements in HashSet

public int size()
Returns the number of elements in this set.

import java.util.*;

class HashSetSize{
 public static void main(String args[]){
  HashSet<Integer> mySet = new HashSet<> ();
  
  for(int i=0; i < 5; i++){
   System.out.println("\nAdding "+i+" to mySet");
   mySet.add(i);
   System.out.print("Elements in mySet are ");
   System.out.println(mySet);
   System.out.println("Size of mySet : " + mySet.size());
  }
 } 
}

Output

Adding 0 to mySet
Elements in mySet are [0]
Size of mySet : 1

Adding 1 to mySet
Elements in mySet are [0, 1]
Size of mySet : 2

Adding 2 to mySet
Elements in mySet are [0, 1, 2]
Size of mySet : 3

Adding 3 to mySet
Elements in mySet are [0, 1, 2, 3]
Size of mySet : 4

Adding 4 to mySet
Elements in mySet are [0, 1, 2, 3, 4]
Size of mySet : 5




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment