Header javaperspective.com
JavaPerspective.com  >   Intermediate Tutorials  >   3. Collections  >   3.2. The class HashSet

3.2. The class HashSet
Last updated: 31 January 2013.

This tutorial explains how to use the class HashSet.

The class HashSet implements the interface Set as an unsynchronized, resizable and unordered collection that does not allow duplicate elements. The sample below shows how to create a HashSet of strings with the default constructor:

Set<String> myHashSet = new HashSet<String>();

The next sample shows how to add elements to the HashSet instance with the method add(E e):

myHashSet.add("Africa");
myHashSet.add
("America");
myHashSet.add
("Antarctica");
myHashSet.add
("Asia");
myHashSet.add
("Europe");

You can iterate over the HashSet instance with a for-each statement like this:

for(String s : myHashSet)
   
System.out.println(s);

You can also use an iterator as shown below:

Iterator<String> iterator = myHashSet.iterator();

while(iterator.hasNext())
   
System.out.println(iterator.next());

The class HashSet provides other useful methods such as contains(Object key), isEmpty, remove(Object key), clear and size. Further details about these methods can be found in the Java API documentation.


You are here :  JavaPerspective.com  >   Intermediate Tutorials  >   3. Collections  >   3.2. The class HashSet
Next tutorial :  JavaPerspective.com  >   Intermediate Tutorials  >   3. Collections  >   3.3. The class HashMap

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7