Java Foundation--collection (Set)

Source: Internet
Author: User
Tags comparable

Attention:

If HashSet stores custom objects, be sure to override Hashcode () &&equals ()

If TreeSet stores custom objects, let the class that the element belongs to implement the natural sort interface comparable, and override CompareTo ()/ Let the constructor of the collection receive a sub-class object of the comparer interface Comparator

structure:
Set:
|--hashset (The underlying structure is a hash table (hash table: The element is an array of linked lists, the hash table depends on the hash value of the storage))
|--linkedhashset (underlying mechanism is linked list and hash table)
|--treeset (Bottom is a two-fork tree structure (red black tree is a self-balancing two-fork tree)

Detailed
Set
unordered (the storage order and the fetch order are inconsistent), unique (although the elements of the set collection are unordered, but as a collection there must be a storage order, and your order of storage is consistent with its order, which cannot be ordered.) )
|--HashSet
HashSet The underlying dependencies are hashcode () and Equals ()
So when you store a custom object, the object needs to override Hashcode () and Equals () to ensure uniqueness (it can be overridden automatically)

HashSet Bottom Source:
①hashset<string> set = new hashset<string> ();
Public HashSet () {
map = new hashmap<> ();
}
②set.add ("Atomic");
Private static Final Object PRESENT = new Object ();
Public boolean Add (E e) {
ReturnMap.put (E, PRESENT) ==null;
}
Source Conclusion: HashSet is a hashmap, its value is stored in the HashMap key, so the HashSet data is unique

if (E.hash = = Hash &&//See Hashcode () First, if the hash value is the same, no element is added
(k = e.key) = = Key | | (Key! = null && key.equals (k)))) {break;} If the element value/address value is the same (element duplicates), no element is added
p = e;//More than three cases before adding elements

TreeSet:The natural sort, the only one (TreeSet bottom is TreeMap
Api:a Navigableset implementation based on A TreeMap
① if it is a basic type, it is automatically sorted to
② if it is a custom type, you need to override ...

The real comparison depends on the element'sCompareTo ()method, and this method is defined in thecomparableThe Inside,
So to rewrite this method, you must first implement the comparable interface, which represents the natural sort
The bottom layer is a two-fork tree structure (the red-black tree is a self-balancing two-fork tree).
Binary tree three kinds of traversal:
Middle sequence Traversal: First left subtree, after root node, then right sub-tree
Pre-sequence traversal: First root node, after left subtree, then right sub-tree
post-the-loop traversal: First left subtree, then right subtree, then root node

SOURCE:①treeset<string> set = new treeset<string> ();
②set.add ("D");

Public boolean Add (E e) {
Return m.put (e,PRESENT) ==null;
}
Private transientNavigablemap<E,Object> m;
Api:a Navigableset implementation based on ATreeMap

TreeMap put ();
Public V put (K key, V value) {
entry<k,v> t = root;
if (t = = null) {
Compare (key, key); Type (and possibly null) check

root = new Entry<> (key, value, NULL);
size = 1;
modcount++;
return null;
}
int CMP;
Entry<k,v> parent;
Split comparator and comparable paths
comparator<? Super k> CPR = comparator;
if (CPR = null) {
do {
parent = t;
CMP = Cpr.compare (key, T.key);//key-t.key
if (CMP < 0)//Key small put left
t = t.left;
else if (cmp > 0)//Key big put right
t = t.right;
Else
return T.setvalue (value);//equal, not put
} while (t! = null);
}
else {
if (key = = null)
throw new NullPointerException ();
@SuppressWarnings ("Unchecked")
comparable<? Super k> K = (comparable<? super K>) key;
do {
parent = t;
cmp = K.compareto (t.key);
if (CMP < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
Else
return T.setvalue (value);
} while (t! = null);
}
entry<k,v> e = new entry<> (key, value, parent);
if (CMP < 0)
Parent.left = e;
Else
Parent.right = e;
Fixafterinsertion (e);
size++;
modcount++;
return null;
}


Summary: TreeSet sets the principle of guaranteed element ordering and uniqueness
Uniqueness: Based on whether the return value of the comparison is determined by
Sort:
A: Natural sorting (elements are comparative)
Enables the class that the element belongs to to implement the natural sort interface comparable
B: Comparator sorting (collection with comparison)
Let the constructor of the collection receive a subclass object of the comparer interface comparator
Example: A:
Mode 1:
treeset<student> ts1 = new treeset<student> ();
If a class wants to sort naturally, it must implement the natural order interface
public class Student implements comparable<student>{
private String name;
private int age;
@Override
public int compareTo (Student o) {
By age, main condition
int num = this.age-o.age;
Secondary conditions, when the same age to see whether the name is the same
If the name and age are the same, it's an element.
int num2 = num = = 0?this.name.compareto (o.name): num;
return num2;

/* Sort by name
@Override
public int compareTo (Student o) {

By name, main condition
int num = this.name.length ()-o.name.length ();
The same name does not mean the same content
int num2 = num = = 0?this.name.compareto (o.name): num;
Name length and content is the same, does not mean the same age
int num3 = Num2 = = 0?this.age-o.age:num2;
return num3;
}
*/
}

B:
Mode 2
treeset<student> ts2 = new Treeset<student> (new Mycomparator ());
Implementing the Comparator () interface
public class Mycomparator implements comparator<student> {
@Override
public int Compare (Student O1, Student O2) {
By name, main condition
int num = O1.getname (). Length ()-o2.getname (). Length ();
The same name does not mean the same content
int num2 = num = = 0? O1.getname (). CompareTo (O2.getname ()): num;
Name length and content is the same, does not mean the same age
int num3 = Num2 = = 0? O1.getage ()-O2.getage (): num2;
return num3;
}
}
Mode 3 (anonymous class mode)
treeset<student> Ts3 = new Treeset<student> (New Comparator<student> () {
@Override
public int Compare (Student O1, Student O2) {
By name, main condition
int num = O1.getname (). Length ()-o2.getname (). Length ();
The same name does not mean the same content
int num2 = num = = 0? O1.getname (). CompareTo (O2.getname ()): num;
Name length and content is the same, does not mean the same age
int num3 = Num2 = = 0? O1.getage ()-O2.getage (): num2;
return num3;
}
});

Java Foundation--collection (Set)

Related Article

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.