Export (0) Print
Expand All

HashSet Class

Visual Studio 2005

Represents a unique collection of elements that are sorted according to their hash value, and can each exist only once in the collection.

Package: java.util

Assembly: vjslib (in vjslib.dll)


public class java.util.HashSet
    extends java.util.AbstractSet
    implements java.util.Set, java.lang.Cloneable, java.io.Serializable

The following example demonstrates the add, contains, isEmpty, iterator, remove, and size methods of the HashSet class.

// hashset_overview.jsl

import java.util.*;

public class Program
{
    public static void main(String[] args)
    {
        // Populate a HashSet with three integers.
        HashSet hs = new HashSet();
        hs.add(new Integer(1));
        hs.add(new Integer(2));
        hs.add(new Integer(2));
        hs.add(new Integer(3));

        // Determine the size of the HashSet.
        System.out.println("The HashSet contains " +
            hs.size() + " elements.");

        // Iterate over the contents of the HashSet.
        Iterator iter = hs.iterator();
        while (iter.hasNext())
        {
            System.out.println(iter.next().toString());
        }

        // Determine if an element exists, and if it does,
        // remove it.
        if (!hs.isEmpty())
        {
            Integer toRemove = new Integer(2);
            if (hs.contains(toRemove))
            {
                if (hs.remove(toRemove))
                {
                    System.out.println("Successfully removed element " +
                        toRemove.toString());
                }
            }
        }
    }
}

/*
Output:
The HashSet contains 3 elements.
1
2
3
Successfully removed element 2
*/

Community Additions

ADD
Show:
© 2014 Microsoft