Possibility and Probability

Coding Python and making businesses…

16 August 2009

Java Set

by admin

Having a list of items is pretty useful. Sometimes its really useful to have no duplicates in that list. Java helps you to do this via the Set interface and its various implementations. The Set interface basically defines a class that will hold a set of objects, and in the process not allow duplicates. (If you are ok with having duplicate items look into using something like ArrayList.) Like other things in the Collection family, Sets have an iterator() method that will provide you with an iterator so you can access the items being held by the set. One example of a Set implementation (and probably one of the most common implementations of Set) is the HashSet. HashSet simply stores objects passed to it via the add() method according to its own internal heuristic. If you need to control the order that items are read from the Set (i.e. the objects should come out in alphabetical order) then the TreeSet class is the weapon of choice. TreeSet uses a Comparator that you can set (optionally) that will allow the set to order the objects as they are added. This is enormously useful when your code receives some data from some source (a database, a web source, etc.) and you want to make sure that the data is sorted and is unique. Sets pop up in several places in Java, one of the most notable is in Maps. Since a map is a key-value data structure, the keys should be unique. As a result, if you call keySet() on a Map you will get a collection of the keys for that map, and it will be a Set object.

tags: