set Interface
Set sets are unordered, elements are not repeatable
Common collection classes are HashSet and TreeSet
HashSet class
Each of the two list collections has its advantages, so is there a collection of the advantages of both of these list sets? The answer is yes, the set set.
Example: package collection.set.hashset;import java.util.hashset;import java.util.iterator;/** * Demo hashset * @author Genius Alliance - Yukun */public class hashsetdemo { Public static void main (String[] args) {//Create HashSet object hashset hs = new hashset ();//loop adds element for (int i = 0; i < 10; i++) to the set HS {// Create a Person object Person p = new person ();//Assign a value to the Name property of the Person object//There is a known, the order of accession is Zhao 0, Zhao 1, Zhao 2 ... Zhao 9p.name = "Zhao" + i;//the person object p into the set Hs.add (p);} /* * iterator (iterator): Provides a way to access each element in the collection collection * iterator is an interface * defines the Hasnext () method That determines whether the set contains the next element * returns True if there is a next element, or vice versa, and returns false * also defines the next () method, which gets the next element * A iterator () method is defined in collection to get the iterator object * * because the set collection cannot use the subscript to access the element, the collection element cannot be traversed in the same way as the subscript * So Java provides us with Iterator for accessing individual elements in the collection &NBSP;*/ITERATOR&NBSP;IT&NBSP;=&NBSp;hs.iterator ();//Call the Hasnext method to determine if there is another element in the collection while (It.hasnext ()) {//Call the next method to get the next element object obj = It.next ();//force type Conversion person p = (person) obj;//output the Name property value, and the order of the join is different System.out.print (p.name + " ");}} Person class Class person{public string name;} The result of running on my machine: Zhao 4 Zhao 7 Zhao 8 Zhao 0 Zhao 6 Zhao 1 Zhao 3 Zhao 5 Zhao 9
from the above results can be seen, the order of the output is not added in the order (may not be able to run a disorderly sequence of effects, you can instantly click on the eclipse on the Run button, so that the effect of disorderly order to see a greater probability); so called set is a set of unordered.
So how does set have the advantage of implementing both list sets at the same time, and why is there no order?
First set uses both the structure of the list collection, that is, the array + linked list (set is used in the single list: one node only stores the next node, not the previous node); where each of the positions in the array is used to store the first element of a list.
We have to mention hashcode and equals. When creating a subclass object for a set collection, a node[] table (node array) is created to store the node object, and node stores the next node and the element that joins the collection.
When you add element A to the collection, set creates a Node object NodeA (Node NodeA = new node ()), assigns element A to the key property in NodeA (Nodea.key = A), The subscript is then computed based on the hashcode value of element a (if the resulting subscript is 1), and the address of the NodeA is then assigned to the position of the subscript 1.
When you add element B to the collection again, the node object NodeB is created, and the subscript computed using the hashcode value of element B is also 1, and the Equals method is used to determine whether the two objects, element A and element B, are the same.
If Equals returns True, the contents of a and B are the same, and NodeB is not added to the collection at this time.
If the Equals method returns false, stating that element A and element B are different two objects, the NodeB is assigned to the next property in NodeA (Nodea.next = NodeB), which forms the single-necklace table structure.
From the above description, we can not add duplicate elements in set, and can not quickly get a specified element from the set, we can only get each element in the set by using iterator to provide us with a way to iterate through the collection.
Example diagram
650) this.width=650; "src=" http://img.blog.csdn.net/20150812161945262 "/>
The table created above is called a hash table or hash table with a default initial length of 16 (if you customize the initial capacity when you create the collection object, the custom capacity value must be a full multiple of 2). The load factor defaults to 0.75 (when the number of elements added in the collection equals the current length multiplied by the load factor, the collection automatically increases the capacity to twice times the original).
Read more: "I genius official free Tutorial 37: One-way list structure of Java data structure"
The subscript is computed using the hashcode value of key (calculation method: int h = Key.hashcode (); int hash = h^ (h>>>16); int index = (table.length-1) & hash), which guarantees no cross-border, but cannot guarantee the order, so the set set is unordered.
The advantage of this is that when elements are added and removed, there is no need to displace the elements in the array, simply by adding and deleting the results from the computed subscript and the Equals method.
The disadvantage is that there is no order to quickly get an element, and it must be traversed to get the elements in the set collection.
In addition, you can use the Hashcode method in the Override object class to control what objects can produce a consistent subscript (the node object in the hash table). This is then used to override the Equals method of the object class to control whether objects belong to duplicate objects. And it is necessary that the results of the two methods satisfy the requirements at the same time that the two objects are the same object, and either method does not satisfy the requirements and is considered to be different objects.
Example: package collection.set.hashset;import java.util.hashset;import java.util.set;/** * Demo Overriding the Hashcode method and the Equals method * * @author Genius Federation - Yukun */public Class hashcodeequalsdemo {public static void main (String[] args) {/* * created a Personhe type object in heap memory * object that holds "Zhang San" and "123456789" two strings */personhe p1 = new personhe ("Zhang San", "123456789", 10);/* * also creates a Personhe type object in heap memory * object that is also saved in the " Zhang San "and" 123456789 "Two strings */personhe p2 = new personhe (" Zhang San ", " 123456789 ", 20);/* * at this time there are two objects of type Personhe in memory * if the Personhe class does not override the Equals method of the parent object * Then the Equals method in the object class is compared * the same as using = =, the result is: False */system.out.println (P1&NBSP;==&NBSP;P2);/* * now has overridden the Equals method, and the name and the * * * * * * * * * * * * * * * are equal to the same value as the name and the * * * * * So this is the result of using equals: true */system.out.println (P1.equals (p2));//Create HashSet object (parent class reference to child class object) Set sethe = new hashset ();//add Element Sethe.add (p1) to the collection;/* * personhe overrides the Hashcode method and the Equals method * makes the hashcode of the object P1 and P2 equal, the result of equals is true * so the object P2 is not added to the collection */sethe.add (p2);/* * can use the Iterator + while loop to get the elements in the set collection * can also use the enhanced for loop * syntax format: for (data type variable name : inherit collection or array of collection interfaces) {} * Function: Loops Remove an element assignment variable from a collection or array at a time * note: Declaring a variable's data type must be able to receive the type * inverse of the elements taken out of the collection or array: string[] str = {"abc", "xyz"}; * for (INT&NBSP;I&NBSP;:&NBSP;STR) {}; * executes the first loop, takes out the string ABC, Assign to a variable of type int i * This is obviously wrong */for (object obj:sethe) {personhe phe = (PersonHE) obj;/* * due to the inclusion of the previous object P1 is overwritten * so this will only be output once, and the output is the object p1 * output: Name: Zhang San *** Number:123456789 Age: 10 */system.out.println (PHE);}} /** * Create human personhe * @author Genius Alliance - Yukun */class personhe{//Name private string name;//*** private string id;//age public int age;// Declaration with parameter construction method Public personhe (string name, string id, int age) {this.name = Name;this.id = id;this.age = age;} /** * overriding the hashcode * purpose of the parent class: Customizing the algorithm for calculating hash values */@Overridepublic int hashcode () {/* * Here The custom calculation rule is that the name of the hash value or the hash value of the * * Number * Of course the algorithm is not fixed, as long as the requirements can be met * The use or operation is just to minimize the occurrence of the same situation */return name.hashcode () ^ id.hashcode ();} /** * overriding the Equals method of a parent class * purpose: Customizing the Rules for comparing the contents of two objects */@Overridepublic boolean Equals (object obj) {//the Object coercion type to personpersonhe p = (personhe) obj;//The custom comparison rule here is, When the name and the number are the same, it means the same person boolean result = this.name.equals (P.name) && This.id.equals (p.id); return result;} /** * overriding the parent class's ToString Method * purpose: Customizing the Rules for converting objects to strings */@Overridepublic strinG tostring () {//The custom rule here is The string that returns the name and the number return "name:" + name + " *** No.: " + id + " Age: " + age;}} Running Result: Falsetrue name: Zhang San province No.:123456789 Age: 10
Summarize:
The set set is unordered, non-repeatable, with hash (hash) storage (array + unidirectional list), Iterator + loop and enhanced for loop, Iterator (iterator) Main method: Hasnext () and Next (), Determines whether the two objects added to the collection are duplicates:
1, judge whether the hashcode is the same;
When Hashcode is the same, but equals evaluates to False, two objects are saved on a one-way list, a one-way list called "Buckets"
2, use equals to determine whether the content is the same;
When equals compares the result to true, but Hashcode is different, two objects are saved in a different "bucket"
TreeSet class
Since the set set is unordered, can you add another method to set the sort? The answer is yes.
Java provides us with the TreeSet class, which automatically sorts the elements that join the set set. However, the element type required to join the TreeSet collection must implement the comparable interface and implement the CompareTo () method in the interface to customize the ordering in the method.
Instance:package collection.set.treeset;import java.util.treeset;/** * demonstrates the generic TreeSet collection * @author Genius Alliance - Yukun */public class treesetdemo {public static void main (String[] args) {//creates three branch objects branch b1 = new branch ("Branch 10", &NBSP;10); Branch b2 = new branch ("Branch 5", 5); Branch b3 = new branch ("Branch 8", 8);//Create TreeSet Collection Object treeset ts = new TreeSet ();//Add elements to the collection; The element type that joins the TreeSet collection must implement the comparable interface Ts.add (B1); Ts.add (B2); Ts.add (b3);//enhanced for loop traversal collection tsfor (object obj : ts) {//forced type conversion branch b = (Branch) obj;// Output System.out.println ("Name:" + b.getname () + " Ring" + b.getannualring ()) ;}}} /** * Branch class branch * The element type that joins the TreeSet collection must implement the comparable interface * the exception will occur when the program is run * @author Genius Alliance - Yukun &NBSP;*/CLASS&NBSP;BRANCH&NBSP;IMPLEMENTS&NBSP; comparable{//identification name private string name;//ring: The basis for sorting private int annualring;//method public with parameter construction branch (string name, int annualring) {this.name = name;this.annualring = annualring;} Override the method in the interface @overridepublic int compareto (object o) {//Force type conversion branch b = ( Branch) o;/* * Use the ring as the basis for sorting comparison * current object ring minus parameter The age * result of the incoming Branch object is equal to 0 for: two branches with the same ring * results greater than 0 means: The current object has a large ring, followed by * the result is less than 0 means: The Parameter object has a large ring, and is in the back */int result = This.annualring - b.annualring;return result;} Gets the name Public string getname () {return name;} Get Ring public int getannualring () {return annualring;}} Operation Result: Name: Branch 5 Ring 5 name: 8 Tree Ring 8 name: Branch 10 Ring 10
This article from the "Genius Union Education Official Blog" blog, reproduced please contact the author!
I genius official free Tutorial 32: Set Set of Java collection framework