Using collections in Java: sets

A List such as an ArrayList is useful in cases where we want to store some arbitrary large group of objects in a fixed order, and possibly refer to those objects by their position in the list. But a list is not so good for another type of problem where:

A collection in which an object may be "present or not" (but not present multiple times) is called a set.

Why use a set?

It may have occurred to you that you could use a plain old list for the above purpose. After all, List has a contains() method to see if a given object is in the list, and to preserve the present-or-not condition, we could just check before adding if the given object was already in the list, and if so not add it again. So what's the point of a "set"?

The point is simply efficiency:

If your only necessary criterion is present or not and you don't need the extra functionality of a list (such as ordering, being able to retrieve the nth item), then it is possible to use a more efficient data structure. That's generally what Java's set implementations do.

Next: introducing the HashSet

On the next page, we look at how to use a Java set, with the introduction of the HashSet class.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.