Subscribe To MegiSoft RSS Feeds!     Your Browser OR  Google Feedburner

Java HashSet

HashSet is one of the classes of the Java standard library. It is a subclass of the class AbstractSet and implements the interfaces Set<E>, Collection<E>, Iterable<E>, Serializable, Cloneable. The order of the elements in this class does not guarantee to remain constant over time. This class allows null element.

The following UML diagram shows the position of the class HashSet in the hierarchy.

Articles: ArrayList  HashSet  TreeSet  HashMap  TreeMap 
Quizzes: Java Collection Quizzes 

hashset-hierarchy

What is a HashSet in Java?

A HashSet is a data structure that allows you to collect elements. It is one of the classes in the Java library, which contains different methods to add, remove elements and more. To use it in your own classes, you need to import the package “java.util” from the Java library  as shown below.

import java.util.HashSet;

 

Is HashSet my best Java collection class choice?

To answer the question whether HashSet is your best choice, you need to know more details about it as well as about other Java collection classes. The information and the exercises below will help you to make that decision.

  1. HashSet implements Set interface.
  2. The elements of a HashSet doesn’t guarantee any order.
  3. Adding a duplicate element to a HashSet, results in overwriting the old element, because it does not allow duplicates.
  4. It is possible to add null value to a HashSet.
  5. HashSet is unsynchronized.

The following exercises show some important methods of what you can do with the elements of a HashSet.

 

Exercise 1A: How to create a Java HashSet and add elements to it?

  • Create a HashSet “nameSet” and add the following names to it: Nora, Thomas, Lily, Charles, David, Ella.

Exercise 1B: How to find the size of a Java HashSet?

  • Print the size of the HashSet to the standard output before and after adding the names.

Answer 1:

  • A- The following code adds the mentioned names to the HashSet nameSet.
  • B- The program writes the following to the standard output when it is compiled and run.

nameSet size before adding the names: 0
nameSet size after adding the names: 6

import java.util.HashSet;

public class TestHashSet {

	public static void main(String[] args){

		HashSet<String> nameSet = new HashSet<String>();
		System.out.println("nameSet size before adding the names: " + nameSet.size());

		nameSet.add("Nora");
		nameSet.add("Thomas");
		nameSet.add("Lily");
		nameSet.add("Charles");
		nameSet.add("David");
		nameSet.add("Ella");
		System.out.println("nameSet size after adding the names: " + nameSet.size());
	}
}

Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Exercise 2: How to retrieve the elements of a Java HashSet and print them to the standard output?

  • Add a piece of code to the exercise 1 to print all the names to the standard output.

Answer 2:

  • When the program is compiled and run, it writes the following names to the standard output.

Print the names to the standard output
David Lily Thomas Nora Ella Charles
Another method to print the names to the standard output
David Lily Thomas Nora Ella Charles

import java.util.HashSet;
import java.util.Iterator;

public class TestHashSet {

	public static void main(String[] args){

		HashSet<String> nameSet = new HashSet<String>();
		nameSet.add("Nora");
		nameSet.add("Thomas");
		nameSet.add("Lily");
		nameSet.add("Charles");
		nameSet.add("David");
		nameSet.add("Ella");

		System.out.println("Print the names to the standard output");
		Iterator<String> iter = nameSet.iterator();
		while(iter.hasNext()) {
			System.out.print(" " + iter.next());
		}
		System.out.println();
		System.out.println("Another method to print the names to the standard output");
		for(String temp:nameSet) {
			System.out.print(" " + temp);
		}
	}
}

Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Exercise 3: How to associate the contents of two HashSets in one?

  • Create two HashSets “group1” and “group2”.
  • Add the names “Olivia, Mia, Alexander, Mason, James” to the first group1.
  • Add the names “Joseph, Mia, Mila, Olivia, James, Charlotte” to the second group2.
  • Create a new HashSet “allNames” and add both group names to it.

HashSet doesn’t allow duplicates that is why it overwrites the duplicates automatically.

Answer 3:

  • When the program is compiled and run, it writes the following names to the standard output.

Group1: [James, Mia, Olivia, Mason, Alexander]
Group2: [James, Joseph, Mia, Mila, Olivia, Charlotte]
Both Groups: [James, Joseph, Mia, Mila, Olivia, Charlotte, Mason, Alexander]

 

import java.util.HashSet;
import java.util.Set;

public class TestHashSet {

	public static void main(String args[]){
		Set group1,group2,bothGroups;
		group1 = new HashSet();
		group2 = new HashSet();

		group1.add("Olivia");
		group1.add("Mia");
		group1.add("Alexander");
		group1.add("Mason");
		group1.add("James");

		group2.add("Joseph");
		group2.add("Mia");
		group2.add("Mila");
		group2.add("Olivia");
		group2.add("James");
		group2.add("Charlotte");

		bothGroups = new HashSet(group1);
		//The duplicates appear only ones
		bothGroups.addAll(group2);

		System.out.println("Group1:     " + group1);
		System.out.println("Group2:     " + group2);
		System.out.println("Both Groups:  " + bothGroups);
	}
}

Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Articles: ArrayList  HashSet  TreeSet  HashMap  TreeMap 
Quizzes: Java Collection Quizzes 
Megisoft.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes. The author of Megisoft is Sar Maroof who has more than a decade of experience with web development mainly with Java, MySql, HTML and more..

Suggested Articles:


Click Here For Info about: Sar Maroof's New Java Book
Author: Sar Maroof
More than a decade of experience with developing web applications mainly with Java.
Sun Certified JSP as well as EJB
CIW Certified Internet Webmaster - Mind IT
Applied Science in Physics HBO Amsterdam
Bachellor Science in Physics at Basra university.
 Subscribe To Megisoft RSS Feeds! (Your Browser)
 Mail This Page To A Friend!
 Bookmark This Page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

2 Comments

Add a Comment
  1. Great line up. We will be linking to this excellent
    article on our site. Keep up the good writing.

  2. Thanks for shianrg. Always good to find a real expert.

Leave a Reply

megisoft © 2016