Set of collection

Source: Internet
Author: User
Tags comparable

Collection list: Click on the Open link

As with the list collection, the Set collection inherits the collection interface.

HashSet and TreeSet are two classes that we often use.

HashSet and TreeSet both inherited the Abstractset abstract class: But TreeSet implemented the SortedSet interface:



So TreeSet is ordered (because it is a data structure of a red-black tree, a balanced binary tree (AVL tree), as the following will be said) HashSet

All I know is that set a big feature is to go heavy, the collection will not have the same object (if the value of the two objects stored in HashSet the same Equals method returns the result is true, then hashset that the two elements are the same element, Store only one (duplicate elements cannot be deposited))

Add Method:


Here e is the data we want to store, the present is an object, a map is set in the HashSet, the value of the map key is stored, and the value holds a fixed object, which is the adapter pattern (the operation that is understood as set is appropriate to the map.) design mode I know the best or the single case mode, the adapter mode just read a little, that is not too much to say.

Enter the Map.put method:

 Public V-Put (K key, V value) {//For key hash return Putval (hash (key), key, value, false, true);
     }/** * Implements Map.put and Related methods * * @param hash hash for key * @param key * @param value the value to put * @param onlyifabsent if true, don ' t change existing value * @param evict I
     f false, the table is in creation mode.
                   * @return Previous value, or null if none */FINAL V putval (int hash, K key, V value, Boolean onlyifabsent, Boolean evict) {hashmap.node<k,v>[] tab; Hashmap.node<k,v> p;
           int n, I;
        Rable is defined at the beginning: transient node<k,v>[] table; if (tab = table) = = NULL | |
            (n = tab.length) = = 0//resize is the expansion method, with the following resize description n = (Tab = resize ()). length; To compute the hash value based on the key value keys I, if table[i]==null, add the IF (p = tab[i = (n-1) & hash) to a new node (= = null) ta B[i] = NewNode (hash, key, value, null); else {hashmap.node<k,v> E;
            K K; To determine if an incoming object is equal and equal to replace if (P.hash = Hash && (k = p.key) = key | |
                (Key!= null && key.equals (k)))
                e = p;
                Determine if Table[i] is a TreeNode, i.e. table[i] is a red-black tree, and if it is a red-black tree, insert the key value directly in the tree to else if (p instanceof Hashmap.treenode)
                E = ((hashmap.treenode<k,v>) p). puttreeval (This, tab, hash, key, value);
                The chain is linked list, use the chain address method else {//traversal table[i], to determine whether the chain table length is greater than treeify_threshold (the default value is 8), greater than 8, the list converted to red and black trees,
                    Insert operation in the red and black tree, otherwise the insert operation of the linked list; If the key already exists in the traversal process, the value can be overwritten directly; for (int bincount = 0;; ++bincount) {
                        if ((e = p.next) = = null) {P.next = NewNode (hash, key, value, NULL);
                        if (bincount >= treeify_threshold-1)//-1 for 1st treeifybin (tab, hash); BreAk } if (E.hash = = Hash && (k = e.key) = = Key | |
                        (Key!= null && key.equals (k)))
                    Break
                p = e;
                } if (e!= null) {//Existing mapping for key V oldValue = E.value;
                if (!onlyifabsent | | oldValue = = NULL) E.value = value;
                Afternodeaccess (e);
            return oldValue;
        }} ++modcount;
        if (++size > Threshold) resize ();
        Afternodeinsertion (evict);
    return null; }

 Final node<k,v>[] Resize () {//resize method is for HASHMAP expansion, its default length is 1<<4 maximum is 1 << 30.
        Click on your own to see, here roughly say: node<k,v>[] oldtab = table; int Oldcap = (Oldtab = null)?
        0:oldtab.length;
        int oldthr = threshold;
        int Newcap, newthr = 0;
            if (Oldcap > 0) {//if oldcap> 0, and map maximum capacity is greater than or equal to 1<<30 return Oldtab, that is, n equals the original container length, is not expanded, direct return
                if (Oldcap >= maximum_capacity) {threshold = Integer.max_value;
            return oldtab; //If oldcap> 0, and Oldcap expands twice times less than 1<<30 and Oldcap is greater than or equal to 1<<4, then the expansion is twice times else if (Newcap = ol
                DCap << 1) < maximum_capacity && Oldcap >= default_initial_capacity) Newthr = Oldthr << 1;  Double threshold}//If the container is not 0,oldthr>0, this is not initialized, where the new container capacity equals oldthr else if (Oldthr > 0)//
       Initial capacity is placed in threshold     Newcap = Oldthr;
            Default_load_factor is the load factor 0.75 else {//Zero initial threshold signifies using defaults
            Newcap = default_initial_capacity;
        NEWTHR = (int) (Default_load_factor * default_initial_capacity); //if Newthr = = 0 that is, if twice times the expansion is greater than 1<<30, the upper bound of the capacity is recalculated Newnode[newcap] if (newthr = 0) {Floa
            t ft = (float) newcap * loadfactor;
                    Newthr = (Newcap < maximum_capacity && ft < (float) maximum_capacity?
        (int) Ft:Integer.MAX_VALUE);
        } threshold = Newthr;
        @SuppressWarnings ({"Rawtypes", "Unchecked"}) node<k,v>[] Newtab = (node<k,v>[)) new Node[newcap];
        Table = Newtab;
                if (Oldtab!= null) {//is not explained here, move Oldtab to Newtab for (int j = 0; j < Oldcap; ++j) {
                Node<k,v> e; if ((e = oldtab[j])!= null) {Oldtab[j] = nulL
                    if (E.next = = null) Newtab[e.hash & (newCap-1)] = e;
                    else if (e instanceof TreeNode) ((treenode<k,v>) e). Split (This, Newtab, J, Oldcap);
                        else {//preserve order node<k,v> Lohead = null, lotail = NULL;
                        Node<k,v> hihead = null, hitail = NULL;
                        Node<k,v> Next;
                            do {next = E.next;
                                    if ((E.hash & oldcap) = = 0) {if (Lotail = null)
                                Lohead = e;
                                else Lotail.next = e;
                            Lotail = e;
                                    else {if (Hitail = null) Hihead =E
                                else Hitail.next = e;
                            Hitail = e;
                        } while ((E = next)!= null);
                            if (lotail!= null) {lotail.next = null;
                        NEWTAB[J] = Lohead;
                            } if (Hitail!= null) {hitail.next = null;
                        Newtab[j + oldcap] = Hihead;
    }}} return newtab; }

This way, the duplicated objects are not added. But sometimes we come out with the new two identical objects.


In this case, we should rewrite the Javaobject hashcode and Equals method


This time it will be covered. TreeSet

Can go heavy and sort, for the data structure, I know is also the fur, the balance of the time complexity O (log n), I have written before, every time I add elements will be left or right rotation has reached the goal of balance (the tree's left to about 2 depth is greater than or equal to the imbalance):

Click to open the link

Since treeset can be sorted naturally, treeset must have a sort rule.
1: Allow the saved element to customize the comparison rule.
2: Specify the collation for TreeSet.
Mode one: The elements themselves have a comparative
The element itself has the comparison, needs the element realization comparable interface, the rewriting CompareTo method, namely lets the element own comparison, this way called the element natural sort also is called the default sort.
Mode two: The container has the comparative sex
When the elements themselves do not have a comparative, or their own comparative is not needed. So at this time you can let the container itself. You need to define a class to implement the interface comparator, rewrite the Compare method, and pass the subclass instance object of the interface as a parameter to the TreeMap collection's construction method.
Note: When the comparable comparison mode and the comparator comparison mode exist at the same time, the comparator comparison mode is the main;
Note: When overriding the CompareTo or compare methods, you must compare the minor conditions when you explicitly compare the primary conditions for equality. (assuming that the name and age of people are the same, if you want to sort people by age, if the age of the same person, how to deal with.) You cannot return 0 directly, because you may have different names (people of different ages with the same name). In this case, you need to make a minor conditional judgment (you need to judge the name), only the name and age equal to return 0.

Determine uniqueness by return 0来.

The realization of the way: the elements themselves have a comparative


Mode two realization: The container has the comparative sex

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.