O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Sets

Problem

You want to ensure that only one copy of each unique value is stored in a collection.

Solution

Use a Set.

Discussion

The Set interface is a collection that maintains only one instance of each value. If you add into it an object that is equal (as defined by the equals( ) method) to another object, only one of the objects is maintained. By definition, it does not matter to you which of the two objects it keeps -- the one in the collection or the one being added -- since your objects’ equals( ) method indicated they were both equal.

// SetDemo.java
HashSet h = new HashSet(  );
h.add("One");
h.add("Two");
h.add("One"); // DUPLICATE
h.add("Three");
Iterator it = h.iterator(  );
while (it.hasNext(  )) {
    System.out.println(it.next(  ));
}

Not surprisingly, only the three distinct values are printed.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required