java left logo
java middle logo
java right logo
 

Home arrow Java SE Tips arrow java.util arrow How to use HashSet
 
 
Main Menu
Home
Java Tutorials
Book Reviews
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Java Network
Java Forums
Java Blog




Most Visited Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews
Top Rated Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews


Statistics
Registered Users: 4093
Java SE Tips: 614
Java ME Tips: 202
Java EE Tips: 183
Other API Tips: 779
Java Applications: 298
Java Libraries: 209
Java Games: 16
Book Reviews:
 
 
 
How to use HashSet E-mail
User Rating: / 286
PoorBest 

HashSet class is a concrete implementation of Set interface. It creates a collection that uses a hash table for storage. 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 an index at which the data associated with the key is stored. The transformation of key into its hash code is performed automatically. You never see the hash code itself. The advantage of hashing is that it allows the execution time of basic operation, such as add(), contains(), remove(), and size() to remain constant even for large sets.

HashSet is not synchronized. If more than one thread wants to access it at the same time then it must be synchronized externally.

This code shows the use of HashSet. This will identify the number of duplicate words in a String. The String is passed as command line arguments.

Add() method of the HashSet add the object into the storage if it is not already present.

import java.util.*;

public class FindDups {

  public static void main(String[] args) {
  
    Set s = new HashSet();

    for(int i=0; i<args.length;i++){
      if(!s.add(args[i]))
        System.out.println("Duplicate detected : " + args[i]);
    }

    System.out.println(s.size() " distinct words detected : " + s );
  }
}

Run the program: C:\> java FindDups i came i came i conquered

Output Screen :

Duplicate detected: i
Duplicate detected: i
4 distinct words detected : [came,saw,conquered,i]

 Related Tips

 
< Prev   Next >
 
       
         
     
 
 
 
   
 
 
java bottom left
java bottom middle
java bottom right
RSS 0.91 FeedRSS 1.0 FeedRSS 2.0 FeedATOM FeedOPML Feed

Home - About Us - Privacy Policy
Copyright 2005 - 2008 www.java-tips.org
Java is a trademark of Sun Microsystems, Inc.