| | |
    Java Beginner Home
    Table of Contents
    Introduction to Java
    Getting Started with Java
    Basic Language Elements
    Java Operators
    Java Control Statements
    Java Access Modifiers
    Classes and Objects
    Java Constructors
    Object Serialization
    Java Class Inheritance
    Java Object Type Casting
    Abstract class and Interface
    Java Method Overiding
    Java toString Method
    Java String Class
    Java toString Method
    Java String Comparison
    Java StringBuffer
    Java Exceptions
    Singleton Pattern
    Java Threads Tutorial
    Java Collections Framework
    Java Date Util
    Swing Tutorial
    Feedback
    Java books

Java HashSet

  • The HashSet class implements the Set interface.
  • It makes no guarantee that the order of elements will remain constant over time.
  • This class is not synchronized and permits a null element.
  • This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.
  • To prevent unsynchronized access to the Set: Set s = Collections.synchronizedSet(new HashSet(...)); 




    Below is a HashSet Example showing how collections are manipulated using a HashSet

    import java.util.*;
    
    public class HashSetExample {
    
    	private static String names[] = { "bob", "hemanth", "hhh", "hero",
    			"shawn", "bob", "mike", "Rick", "rock", "hemanth", "mike",
    			"undertaker" };
    	public static void main(String args[]) {
    		ArrayList aList;
    		aList = new ArrayList(Arrays.asList(names));
    		System.out.println("The names elements " + aList);
    		HashSet ref = new HashSet(aList); // create a HashSet
    		Iterator i = ref.iterator();
    		System.out.println();
    		System.out.print("Unique names are: ");
    		while (i.hasNext())
    			System.out.print(i.next() + " ");
    		System.out.println();
    	}
    }

    Output

    The names elements [bob, hemanth, hhh, hero, shawn, bob, mike, Rick, rock, hemanth, mike, undertaker]

    Unique names are: hhh hero bob Rick shawn hemanth rock mike undertaker

     

     
    Page 8 of 8
    1
    8

     

  •  
        Java is a trademark of Sun Microsystems, Inc.
    | | |
    © Copyright 2007-08 javabeginner.com