AbstractSet size() method in Java with Example
The size()
method in the AbstractSet
class of Java returns the number of elements in the set. This method is inherited from the java.util.Set
interface and is implemented in the AbstractSet
class.
Syntax:
public int size()
Example:
import java.util.*;
public class SetExample {
public static void main(String[] args) {
// Creating a set using HashSet
Set<String> set = new HashSet<String>();
// Adding elements to the set
set.add("apple");
set.add("banana");
set.add("orange");
// Printing the size of the set
System.out.println("Size of the set: " + set.size());
}
}
Output:
Size of the set: 3
In the above example, we have created a HashSet
and added three elements to it. We have then printed the size of the set using the size()
method, which returns the number of elements in the set. The output shows that the size of the set is 3.