In order to find out how many elements are in set, you can
use the size() method:
public int size()
You can also use isEmpty() method to check if there is any
element in given HashSet.
public boolean isEmpty()
Sample Program:
import java.util.HashSet;
import java.util.Set;
/**
*
*/
/**
* @author Dixit
*
*/
public class HashSetSize {
/**
* @param args
*/
public static void main(String[] args) {
Set set = new HashSet();
System.out.println("Before adding element");
System.out.println(set.size());
System.out.println(set.isEmpty());
set.add("a");
set.add("b");
System.out.println("After adding element");
System.out.println(set.size());
System.out.println(set.isEmpty());
}
}
Output:
Before adding element
0
true
After adding element
2
false
Happy Reading :)
No comments:
Post a Comment