官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 津南区| 寿阳县| 长阳| 汝南县| 久治县| 乐山市| 扎囊县| 永和县| 富平县| 大方县| 佛山市| 射洪县| 康定县| 汝南县| 白河县| 栖霞市| 甘孜| 韶关市| 溧水县| 麻江县| 太谷县| 弋阳县| 东丽区| 新沂市| 车致| 温州市| 洪湖市| 凤庆县| 庄浪县| 大洼县| 西乡县| 灵寿县| 建昌县| 卫辉市| 日照市| 旬邑县| 武乡县| 马鞍山市| 鹿泉市| 临泽县| 清镇市|