Wednesday 27 May 2015

How to count number of element in HashSet

 Size() Method return number of element in the HashSet.

import java.util.HashSet;
import java.util.Set;

public class CountElement {
   
    public static void main(String[] args) {
       
        Set<String> hs = new HashSet<String>();
        hs.add("java");
        hs.add("php");
        hs.add("html");
        hs.add("javascript");
        hs.add("mysql");

        //print hashset
        System.out.println("hashset = "+hs);
       
       
        /*
         * Returns the number of elements in set. If this set contains more than
         * Integer.MAX_VALUE elements, returns  Integer.MAX_VALUE.
         */
       
        System.out.println("Size of hashset = "+hs.size());
    }

}





Output:


hashset = [javascript, php, html, java, mysql]

Size of hashset = 5

No comments:

Post a Comment