Java Reference
In-Depth Information
Set<String> s2Differences1 = new HashSet<>(s2);
s2Differences1.removeAll(s1);
System.out.println("s1 difference s2: " + s1Differences2);
System.out.println("s2 difference s1: " + s2Differences1);
}
public static void testForSubset(Set<String> s1, Set<String> s2) {
System.out.println("s2 is subset s1: " + s1.containsAll(s2));
System.out.println("s1 is subset s2: " + s2.containsAll(s1));
}
}
s1: [Donna, Ken, John]
s2: [Ellen, Donna, Sara]
s1 union s2: [Ellen, Donna, Ken, John, Sara]
s1 intersection s2: [Donna]
s1 difference s2: [Ken, John]
s2 difference s1: [Ellen, Sara]
s2 is subset s1: false
s1 is subset s2: false
In this example, I kept the two original sets,
s1
and
s2
, unmodified inside methods that performed some
operations on these two sets. However, they could have been modified inside any of these methods. It is not wise
to pass a collection to a method like the way I did in this example if you do not want the method to modify your
collection. The Collections Framework offers a way to get an unmodifiable view of a collection using the
java.util.Collections
class. I will discuss this class and all other features that it offers later in this chapter.
The method
Collections.unmodifiableSet(s1)
will return the unmodifiable version of the
s1
set. Any operation
that attempts to modify an unmodifiable collection results in an
UnsupportedOperationException
.
Sorted Set
A sorted set is a set that imposes ordering on its elements. An instance of the
SortedSet
interface represents a sorted set.
The elements in a
SortedSet
can be sorted in a natural order or using a
Comparator
. A
SortedSet
must know
how to sort its elements as they are added. The sorted set relies on two things to sort its elements:
Comparable
interface, it will use the
compareTo()
method of
elements to sort them. This is called sorting in natural order.
•
If its elements implement the
Comparator
object to use a custom sorting. The implementation class for
SortedSet
is recommended to provide a constructor that will accept a
Comparator
object
to use a custom sorting. If a
Comparator
is specified, the
Comparator
is used for sorting
irrespective of the elements implementing the
Comparable
interface.
•
You can supply a
What would happen if the class of the elements of a
SortedSet
does not implement the
Comparable
interface and
you don't supply a
Comparator
object? The answer is that, in such cases, you cannot add any elements to a
SortedSet
.
Attempting to add an element results in a
ClassCastException
.
The
TreeSet
class is one of the predefined implementation classes for the
SortedSet
interface in the Collections
Framework.