Java Reference
In-Depth Information
s2.add("Eve");
s2.add("Donna");
System.out.println("HashSet: " + s2);
System.out.println("s1.equals(s2): " + s1.equals(s2));
}
}
LinkedHashSet: [John, Adam, Eve, Donna]
HashSet: [Adam, Donna, Eve, John]
s1.equals(s2): true
a Set has a very useful application. You can use it when you are supplied with an unknown number of objects
and you have to keep only unique objects. You can create a Set and add all objects to it. it will keep only unique objects
and ignore the duplicate ones. at the end, you will have only unique objects in your Set .
Tip
You can perform union , intersection, and difference (or minus ) operations on mathematical sets. You can perform
the same operations on sets in Java. For discussing these operations, I assume that you have two sets called s1 and
s2 . The union of two sets (written as s1 U s2 in mathematics) contains elements from both sets with no duplicates.
The intersection of two sets (written as s1 Ç s2 in mathematics) contains elements that are common to both sets. The
difference of two sets, s1 and s2 (written as s1 - s2 ), is a set that contains all elements of s1 that are not in s2 . Here is
how you perform these Set operations:
// Union of s1 and s2 will be stored in s1
s1.add(s2);
// Intersection of s1 and s2 will be stored in s1
s1.retainAll(s2);
// Difference of s1 and s2 will be stored in s1
s1.removeAll(s2);
Note that during the set operations such as union, intersection, and difference, the set on which you perform the
operation is modified. For example, s1 is modified if you perform s1.addAll(s2) to compute the union of s1 and s2 .
If you want to compute the union of two sets and keep the original set unchanged, you must make a copy of the original
set before you perform the union operation, like so:
// Compute the union of two sets by keeping the original set unchanged
Set s1Unions2 = new HashSet(s1); // Make a copy of s1
// Now, s1Unions2 is the union of s1 and s2 and both s1 and s2 are unchanged
s1Unions2.addAll(s2);
In mathematics, you can test if a set s1 is a subset of another set s2 . Set s1 is a subset of set s2 if set s2 contains
all elements that are also present in set s1 . You can use the s2.containsAll(s1) method to test if s1 is a subset of s2 .
This method will return true if s1 is a subset of s2 . Otherwise, it will return false .
 
 
Search WWH ::




Custom Search