| Email article link |
| Java Recipe of the Day
The following recipe is from The Java Cookbook, by Ian Darwin. All links in this recipe point to the online version of the book on the Safari Bookshelf. Buy it now, or read it online on the Safari Bookshelf. |
7.10. Eschewing Duplication
. 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 indicates they are 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.
View the past week's recipes: Today | Yesterday | 3 days ago | 4 days ago | 5 days ago | 6 days ago | A week ago
