HashSet properties

In this chapter you will learn:

  1. Get the size of a hash set
  2. Is a HashSet empty

Get the size of a hash set

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

import java.util.HashSet;
//from j av a 2 s. com
public class Main {
  public static void main(String args[]) {
    HashSet<String> hs = new HashSet<String>();

    hs.add("java2s.com");
    hs.add("A");
    hs.add("D");
    hs.add("E");
    hs.add("C");
    hs.add("j a v a2s.com");
    System.out.println(hs.size());
    hs.remove("A");
    System.out.println(hs.size());
  }
}

The output:

Is a HashSet empty

boolean isEmpty() Returns true if this set contains no elements.

import java.util.HashSet;
/*from  j  av  a  2 s . c  o m*/
public class Main{
    public static void main(String args[]) {
        HashSet<String> hs = new HashSet<String>();

        hs.add("java2s.com");
        hs.add("A");
        hs.add("D");
        hs.add("E");
        hs.add("C");
        hs.add("j a v a2s.com");

        System.out.println(hs.isEmpty());
    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. What is TreeSet
  2. How to create TreeSet
  3. Create a TreeSet with custom Comparator
  4. Create TreeSet from a List
Home » Java Tutorial » Set
HashSet
HashSet element adding
HashSet element removing and clearing
HashSet clone
HashSet iterator
HashSet properties
TreeSet
TreeSet elements adding
TreeSet subSet
NavigableSet
LinkedHashSet