The Set Interface

The Set Interface

//Suppose you have a Collection, c, and you want to create 
//another Collection containing the same elements but with all duplicates 
//eliminated. The following one-liner does the trick.

		
Collection<Type> noDups = new HashSet<Type>(c);
import java.util.*;

public class FindDups2 {
    public static void main(String[] args) {
        Set<String> uniques = new HashSet<String>();
        Set<String> dups    = new HashSet<String>();

        for (String a : args)
            if (!uniques.add(a))
                dups.add(a);

        // Destructive set-difference
        uniques.removeAll(dups);

        System.out.println("Unique words:    " + uniques);
        System.out.println("Duplicate words: " + dups);
    }
}

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.

The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.

The Set Interface — Structure map

Clickable & Draggable!

The Set Interface — Related pages: