HashSet element adding

In this chapter you will learn:

  1. How to add elements to a HashSet

Add element to hash set

boolean add(E e) Adds the specified element to this set if it is not already present.

import java.util.HashSet;
//from   j a  v a 2 s  .  c  om
public class Main{
    public static void main(String args[]) {
        HashSet<String> hs = new HashSet<String>();
        hs.add("java2s.com");
        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);
    }
}

The output:

In the code above we adds java2s.com twice into the set but the result only has one java2s.com since set would not allow duplicate elements.

Next chapter...

What you will learn in the next chapter:

  1. How to remove all elements from a HashSet
  2. How to remove an element from hash set
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