HashSet Sample program in Java

By: Kamini Emailed: 1769 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. As most readers likely know, a hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically-you never see the hash code itself. Also, your code can't directly index the hash table. The advantage of hashing is that it allows the execution time of basic operations, such as add( ), contains( ), remove( ), and size( ), to remain constant even for large sets.

The following constructors are defined:

HashSet( )
HashSet(Collection c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)

The first form constructs a default hash set. The second form initializes the hash set by using the elements of c. The third form initializes the capacity of the hash set to capacity. The fourth form initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments. The fill ratio must be between 0.0 and 1.0, and it determines how full the hash set can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash set multiplied by its fill ratio, the hash set is expanded. For constructors that do not take a fill ratio, 0.75 is used. 

HashSet does not define any additional methods beyond those provided by its superclasses and interfaces. Importantly, note that a hash set does not guarantee the order of its elements, because
the process of hashing doesn't usually lend itself to the creation of sorted sets. If you need sorted storage, then another collection, such as TreeSet, is a better choice.

Here is an example that demonstrates HashSet:

// Demonstrate HashSet.
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}

The following is the output from this program:

[F, E, D, C, B, A]

As explained, the elements are not stored in sorted order.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(3)


1. View Comment

it's very usefull to the users who were in starting stage learning about java

View Tutorial          By: Harichandana at 2013-02-28 04:37:17
2. View Comment

Good

View Tutorial          By: Siva Sreekanth at 2013-10-01 16:29:55
3. View Comment

Your output is not correct.. Give the correct output

View Tutorial          By: Surendrakumar at 2014-06-04 07:00:16

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Kamini
Importing the Certificate Reply from the CA example using keytool in Java
The switch Statement example in Java
Joins example in SQL
ERRNO.H Header File in C
XDoclet struts-config.xml in Struts
Macro Substitution using #define in C
Using Checkbox & Radio Tags, html:select, html:options in Struts Forms
Do while Loops in C
Functions in C
Opening files for read and write in C++
Operator Precedence in C++
StringItem sample program in J2ME
AWT-based applications with a User Interface Window in Java
store() and load() example in Java
Stray or Dangling Pointers in C++

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
InetAddress Example program in Java
Read from a COM port using Java program
Stack example in Java - push(), pop(), empty(), search()
How to use ArrayList in Java
Using StringTokenizer in Java
The Basic Structure of a Simple Java program
FileReader and FileWriter example program in Java
Transient vs Volatile modifiers in Java
Vector example in Java
Method Overriding in Java
Method Overloading (function overloading) in Java
instanceof sample program in Java
append() in Java
Student marks calculation program in Java
Reading from a file and writing to a file using Java program
Most Emailed Articles (in Java)
Text to Speech conversion program in Java
inheritance in Java
How to initialize an Array and how to copy the array
Using Charts in JasperReports
What is Unicode?
Operator Precedence in Java
Of Object, equals (), == and hashCode ()
DateFormat sample program in Java
A Simple whois program in Java
CharArrayReader example program in Java
ByteArrayOutputStream - sample program in Java
Vector example in Java
Arrays example in Java - asList(), binarySearch(), fill(), sort(), equals()
HashSet Sample program in Java
Disadvantages of using Native methods in Java