- The Java Workshop
- David Cuartielles Andreas G?ransson Eric Foster Johnson
- 1527字
- 2021-06-11 13:05:24
Sets
Sets within the collections framework are the programmatic equivalent of mathematical sets. This means that they can store objects of a specific type while avoiding duplicates. In the same way, sets offer methods that will let you handle data as you would in mathematics. You can add objects to a set, check whether a set is empty, combine the elements of two sets to add all their elements into a single set, see what objects coincide with each other between two sets, and calculate the difference between two sets.
In the java.util.Sets class, we find three interfaces used to represent sets: HashSet, TreeSet, and LinkedHashSet. The differences between them are straightforward:
- HashSet will store data without guaranteeing the order of iteration.
- TreeSet orders a set by value.
- LinkedHashSet orders a set by arrival time.
Each of these interfaces is meant to be used under specific circumstances. Let's look at a couple of examples of sets, departing from the one in Example05, and look at how we can add other methods to check how to operate sets. The first step is populating a set from an array. There are several methods for doing so; let's use the one that is probably the quickest to implement:
import java.util.*;
public class Example06 {
public static void main(String[] args) {
String[] myArray = new String[] {"3", "25", "2", "79", "2"};
Set mySet = new HashSet();
Collections.addAll(mySet, myArray);
System.out.println(mySet);
}
}
The above line of code shows how to add all the elements of the array to the set; when printing the results, we get:
[2, 79, 3, 25]
Process finished with exit code 0
Please note that the order of the resulting print may vary for you. As explained earlier, HashSet, because of the way it is implemented, cannot guarantee any sorting of the content. If you performed the following example using Integer instead of String for the data, it would end up being sorted:
import java.util.*;
public class Example07 {
public static void main(String[] args) {
Integer[] myArray = new Integer[] {3, 25, 2, 79, 2};
Set mySet = new HashSet();
Collections.addAll(mySet, myArray);
System.out.println(mySet);
}
}
The result of this program is:
[2, 3, 25, 79]
Process finished with exit code 0
This means that the results end up being sorted, even if we don't request it.
Note
The fact that the set in this example is sorted is a mere coincidence. Please be aware that this may not be the case in other situations. Example08 will show the union operation between two sets, and there the data will not be sorted.
Working with sets involves working with packages of data and performing operations with them. The union operation for two sets is displayed in the following example:
import java.util.*;
public class Example08 {
public static void main(String[] args) {
Integer[] numbers1 = new Integer[] {3, 25, 2, 79, 2};
Integer[] numbers2 = new Integer[] {7, 12, 14, 79};
Set set1 = new HashSet();
Collections.addAll(set1, numbers1);
Set set2 = new HashSet();
Collections.addAll(set2, numbers2);
set1.addAll(set2);
System.out.println(set1);
}
}
This program will print, as its output, the resulting set from the union of the two sets described by the two arrays at the beginning of the main method of the example:
[2, 3, 7, 25, 12, 14, 79]
Process finished with exit code 0
Besides HashSet, we also find TreeSet, and here is where data will be sorted by value. Let's simply change the types of the sets in the previous example and see the result:
Set set1 = new TreeSet();
Collections.addAll(set1, numbers1);
Set set2 = new TreeSet();
Collections.addAll(set2, numbers2);
This, when changed in the previous example, will give the following sorted set as a result:
[2, 3, 7, 12, 14, 25, 79]
You might be wondering about the pros and cons of using each type of set. When sorting, you are trading speed for tidiness. Therefore, if you are working with large sets of data and speed is a concern, you will have to decide whether it is more convenient to have the system operate faster, or have the results sorted, which would allow faster binary searches through the dataset.
Given this last modification, we could perform other operations with the data, such as the intersection operation, which is invoked with the set1.retainAll(set2) method. Let's see it in action:
import java.util.*;
public class Example09 {
public static void main(String[] args) {
Integer[] numbers1 = new Integer[] {3, 25, 2, 79, 2};
Integer[] numbers2 = new Integer[] {7, 12, 14, 79};
Set set1 = new TreeSet();
Collections.addAll(set1, numbers1);
Set set2 = new TreeSet();
Collections.addAll(set2, numbers2);
set1.retainAll(set2);
System.out.println(set1);
}
}
For the output, given that the arrays are used to populate the arrays, we will get only those numbers that exist in both arrays; in this case, it is just the number 79:
[79]
Process finished with exit code 0
The third type of set, LinkedHashSet, will sort the objects in order of their arrival. To demonstrate this behavior, let's make a program that will add elements to the set one by one using the set.add(element) command.
import java.util.*;
public class Example10 {
public static void main(String[] args) {
Set set1 = new LinkedHashSet();
set1.add(35);
set1.add(19);
set1.add(11);
set1.add(83);
set1.add(7);
System.out.println(set1);
}
}
When running this example, the result will be sorted by the way the data arrived in the set:
[35, 19, 11, 83, 7]
Process finished with exit code 0
For the sake of experimentation, use the next 2 minutes to chalk out the set construction into HashSet once more:
Set set1 = new LinkedHashSet();
The result of this modified program is uncertain. For example, we get:
[35, 19, 83, 7, 11]
Process finished with exit code 0
This is, again, an unsorted version of the same set of data.
To close our explanation of the possible methods that you can use with sets, let's use LinkedHashSet to run an experiment where we will find the difference between two sets.
import java.util.*;
public class Example11 {
public static void main(String[] args) {
Set set1 = new LinkedHashSet();
set1.add(35);
set1.add(19);
set1.add(11);
set1.add(83);
set1.add(7);
Set set2 = new LinkedHashSet();
set2.add(3);
set2.add(19);
set2.add(11);
set2.add(0);
set2.add(7);
set1.removeAll(set2);
System.out.println(set1);
}
}
In this case, both sets are slightly different, and by determining the difference, the algorithm behind set1.removeAll(set2) will look for the occurrences of each item in set2 within set1 and eliminate them. The result of this program is:
[35, 83]
Process finished with exit code 0
Finally, if you just want to check whether the whole of a set is contained within another set, you can call the set1.containsAll(set2) method. We'll leave that for you to explore – just be aware that the method simply responds with a Boolean stating whether the statement is true or false.
- Java Web及其框架技術(shù)
- Mastering Kali Linux for Web Penetration Testing
- 軟件架構(gòu):Python語言實(shí)現(xiàn)
- GeoServer Beginner's Guide(Second Edition)
- The HTML and CSS Workshop
- 劍指Java:核心原理與應(yīng)用實(shí)踐
- Angular開發(fā)入門與實(shí)戰(zhàn)
- PHP+Ajax+jQuery網(wǎng)站開發(fā)項(xiàng)目式教程
- C專家編程
- C# Multithreaded and Parallel Programming
- C指針原理揭秘:基于底層實(shí)現(xiàn)機(jī)制
- Scala Functional Programming Patterns
- Learning D3.js 5 Mapping(Second Edition)
- Python繪圖指南:分形與數(shù)據(jù)可視化(全彩)
- Expert Cube Development with SSAS Multidimensional Models