Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com

If you need to handle a collection of unique elements, use


  java.util.HashSet
, if the order doesn't matter.

If it does, use
  java.util.TreeSet

instead, which is slower, however.

Create it with an initial capacity for 30 elements

, if it doesn't exist yet.

Add some String objects.

Try to add "car54" again, fails, returns false, since duplicates are not allowed in a Set.

See if "grandpiano" is in the set.

Iterate through the set.

Remove "radiatingphone" by using Iterator's remove method, the only valid way to remove an element while iterating.

Empty the set.

1.5 Generics.

No cast necessary then.

========

NOTES

========

In this example we could have used a Set (=interface) reference instead of HashSet, which can bring some advantages, like passing such a reference to a method, where this method doesn't care whether the instance referred to is actually a HashSet, TreeSet or possibly some other implementation, it can just call the Set interface's methods on it. It can also ease switching to another class later on, if, say, you decide to use TreeSet instead of HashSet. Downside is, that with such a reference you can't call TreeSet's first and last methods, to name but a few. The Set methods are only what the Set-implementing classes have in common and nothing more than that.

=====

It's the same for each collection type, so instead of an ArrayList reference you could use a List reference, f.e.

=====

It's alway possible to cast a Set reference to a TreeSet reference, if that's the instance's actual type, and so call TreeSet-specific methods.