Java Reference
In-Depth Information
You should not try to construct a
TreeSet
of objects without a natural ordering,
such as
Point
objects:
// this code compiles but will lead to a runtime error
Set<Point> points = new TreeSet<Point>();
The preceding code compiles (unfortunately), but it generates an exception when
you run it because it doesn't know how to order the
Point
objects in the
TreeSet
:
Exception in thread "main"
java.lang.ClassCastException: java.awt.Point
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
You'd be better off using a
HashSet
in this case.
In summary, the following are some of the major differences between
HashSet
and
TreeSet
:
Collection
Strengths
• Extremely fast performance for add, contains, and remove tasks
• Can be used with any type of objects as its elements
HashSet
• Elements are stored in sorted order
• Must be used with elements that can be compared (such as
Integer
,
String
)
TreeSet
Consider the task of figuring out how many unique elements appear in two given
sets. You cannot just add the sets' sizes, since they might have some elements in
common that should not be counted twice in your total. Instead, you could count all
elements from the first set and then count only the unique elements of the second, by
checking to see whether each element from the second is also in the first:
// Returns the number of unique elements contained
// in either set1 or set2. Not a good model to follow.
public static int totalElements(Set<String> set1, Set<String> set2) {
int count = set1.size();
for (String element : set2) {
if (!set2.contains(element)) {
count++;
}
}
return count;
}
Search WWH ::
Custom Search