The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util  [50 examples] > Sets  [3 examples]

e352. Creating a Set

A set is a collection that holds unique values. Adding a value that's already in the set has no effect.
    // Create the set
    Set set = new HashSet();
    
    // Add elements to the set
    set.add("a");
    set.add("b");
    set.add("c");
    
    // Remove elements from the set
    set.remove("c");
    
    // Get number of elements in set
    int size = set.size();          // 2
    
    // Adding an element that already exists in the set has no effect
    set.add("a");
    size = set.size();              // 2
    
    // Determining if an element is in the set
    boolean b = set.contains("a");  // true
    b = set.contains("c");          // false
    
    // Iterating over the elements in the set
    Iterator it = set.iterator();
    while (it.hasNext()) {
        // Get element
        Object element = it.next();
    }
    
    // Create an array containing the elements in the set (in this case a String array)
    String[] array = (String[])set.toArray(new String[set.size()]);

 Related Examples
e353. Operating on Sets
e354. Creating a Set That Retains Order-of-Insertion

See also: Arrays    Bits    Collections    Dates    Hash Tables    Lists    Property Files    Sorted Collections    Time    Timers   


© 2002 Addison-Wesley.