Add elements in HashSet

We can use add() method of HashSet to add elements to HashSet collection

boolean add(Object obj)

It adds the element obj to the Set.

Example

  1. import java.util.HashSet;
  2. public class HashSetAddExample {
  3.    public static void main(String args[]) {
  4.      
  5.       HashSet<String> hs =  new HashSet<String>();
  6.  
  7.       hs.add("java");
  8.       hs.add("c");
  9.       hs.add("c++");
  10.       System.out.println(hs);
  11.     }
  12. }
import java.util.HashSet;
public class HashSetAddExample {
   public static void main(String args[]) {
     
      HashSet<String> hs =  new HashSet<String>();

      hs.add("java");
      hs.add("c");
      hs.add("c++");
      System.out.println(hs);
    }
}


Using addAll() method

We can also add another HashSet to existing HashSet using addAll() method

Example :

  1. import java.util.HashSet;
  2. public class HashSetAddAllExample {
  3.    public static void main(String args[]) {
  4.      
  5.       HashSet<String> hs =  new HashSet<String>();
  6.       HashSet<String> hs1 =  new HashSet<String>();
  7.       hs.add("java");
  8.       hs.add("c");
  9.       hs.add("c++");
  10.  
  11.       hs1.add("python");
  12.       hs1.add("oracle");
  13.       hs.addAll(hs1);
  14.       System.out.println(hs);
  15.     }
  16. }
import java.util.HashSet;
public class HashSetAddAllExample {
   public static void main(String args[]) {
     
      HashSet<String> hs =  new HashSet<String>();
      HashSet<String> hs1 =  new HashSet<String>();
      hs.add("java");
      hs.add("c");
      hs.add("c++");

      hs1.add("python");
      hs1.add("oracle");
      hs.addAll(hs1);
      System.out.println(hs);
    }
}
Note : Using addAll() , we can also add elements of another collection like list to HashSet

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on