Hashse, Linkedhashset, TreeSet (Java Basics 17)

Source: Internet
Author: User
Tags addall comparable

1.HashSet Store strings and traverse

* Features: unordered, no index, no repetition

 hashset store string and traverse HashSet  <String> hs = new  hashset<> ();            Hs.add ( "a" );            Hs.add ( "B" );            Hs.add ( "a" );            Hs.add ( "C" );            Hs.add ( "C" );            Hs.add ( "D" );  boolean  B = Hs.add ("D"); //  Returns a Boolean type that returns False when the store is unsuccessful.              System.out.println (b); SYSTEM.OUT.PRINTLN (HS);  //  [d, B, C, a]  * stores strings, is unordered, and does not have duplicate storage. 

2.HashSet Storage of Custom objects guarantees element uniqueness

stores custom objects and guarantees element uniqueness. HashSet<Person> HS =NewHashset<>(); Hs.add (NewPerson ("Zhang San", 23)); Hs.add (NewPerson ("Zhang San", 23)); Hs.add (NewPerson ("John Doe", 24)); Hs.add (NewPerson ("Harry", 25)); Hs.add (NewPerson ("Harry", 25)); Hs.add (NewPerson ("Harry", 25)); Hs.add (NewPerson ("Zhao Liu", 26)); Hs.add (NewPerson ("Zhao Liu", 26)); SYSTEM.OUT.PRINTLN (HS);
* Store custom objects, to make the object have a certain sequential output, and do not repeat, you must override the Hashcode () and the Equals () method, the system comes with, choose to add: Shirt + alt +s +h; The resulting result is: Public inthashcode () {Final intPrime = 31; intresult = 1; Result= Prime * result +Age ; Result= Prime * result + ((name = =NULL) ? 0: Name.hashcode ()); returnresult; }        *Why is it 31? * 1, 31 is a prime number (divisible only by 1 and itself)* 2, 31 This number is neither big nor small.* 3,31 is 2 of 5 times Square-1(2 move left 5 times minus one) Public Booleanequals (Object obj) {if( This= = obj)//The object being called and the object passed in are the same object                return true;//Direct return True            if(obj = =NULL)//the passed-in object is null                return false;//returns false            if( This. getclass ()! = Obj.getclass ())//The byte-code object corresponding to the object that is called is not the same object as the byte-code object for the incoming object                return false;//returns falseperson other = (person) obj;//downward transformation, you can invoke properties and behaviors that are specific to subclasses            if(age! = other.age)//If the age of the calling object is not equal to the age of the incoming object                return false;//returns false            if(Name = =NULL) {//if the name of the call is null                if(Other.name! =NULL)//the passed-in object name is not                    return false;//returns false}Else if(!name.equals (Other.name))//If the name of the calling object and the name of the incoming object are not the same name                return false;//returns false            return true;//returns True}
* To reduce comparisons, optimize the hashcode () code notation.
* The final version is automatically generated.

3.HashSet How to guarantee the principle of element uniqueness

* 1.HashSet principle
* We use set sets are all need to remove the duplicate elements, if at the time of storage by equals () comparison, low efficiency, hashing algorithm to improve the efficiency of de-duplication, reduce the use of the Equals () method of the number of
* When HashSet calls the Add () method to store the object, it first calls the object's Hashcode () method to get a hash value, and then finds in the collection whether there are objects of the same hash value
* If no object with the same hash value is deposited directly into the collection
* If there is an object with the same hash value, the Equals () comparison is performed on the same object as the hash value, and the result of the comparison is false, and true does not exist.
* 2. Save the object of the custom class in HashSet to repeat
* The hashcode () and Equals () methods must be overridden in the class
* Hashcode (): The return value of the same object must be the same, the return value of the property is different (improve efficiency)
* Equals (): property returns True, different property returns False, returns False when storing

Overview and use of 4.LinkedHashSet

* Features: How to save how to take, to repeat, but the order of deposit is the order of output.

Requirement: Write a program that gets 10 random numbers from 1 to 20, requiring random numbers to not be duplicated.        and output the final random number to the console.  Public Static voidMain (string[] args) {HashSet<Integer> HS =NewHashset<> ();//To create a collection objectRandom r =NewRandom ();//Create a random number object             while(Hs.size () < 10) {                intnum = R.nextint (20) + 1;//generate random numbers from 1 to 20hs.add (num); }             for(Integer integer:hs) {//iterating through the collectionSystem.out.println (integer);//Print each element            }        }
*use scanner to read a line of input from the keyboard, remove the repeated characters, and print out the different characters*aaaabbbcccddd* Scanner sc =NewScanner (system.in);//Creating a Keyboard entry object* SYSTEM.OUT.PRINTLN ("Please enter a line string:"); * String line = Sc.nextline ();//Store keyboard-entered strings in line*Char[] arr = Line.tochararray ();//Convert a string into a character array* Hashset<character> HS =NewHashset<> ();//Creating a HashSet Collection Object* for(CharC:arr) {//traversing character Arrays* Hs.add (c);//to add characters from a character array to the collection*    }    * for(Character ch:hs) {//iterating through the collection*System.out.println (CH); *    }
Removes duplicate elements from the collection and ensures the original order          Public Static void getsingle (list<string> List) {            linkedhashsetnew linkedhashset<> ();            Lhs.addall (list);                                     // adds all elements from the list collection to the LHS            List.clear ();                                        // empty the original collection            List.addall (LHS);                                    // Add removed duplicate elements back to list        }

5.TreeSet stores an integer type of element and traverses

*TreeSet Automatic Ascending sort, integer,string type, no Duplicates* 1when customizing an object, implement the comparable interface first, and then override the CompareTo method,*classPersonImplementsComparable<person>{    */*@Override * public int compareTo (person o) {//sorted by age * int num = this.age-o.age; Age as the main condition comparison * return num = = 0? This.name.compareTo (o.name): num;//name as a secondary condition, compare name only when age is same *}*/*/*@Override * public int compareTo (person o) {//Sort by name * int num = This.name.compareTo (o.na        ME); Name as the main condition * return num = = 0?    This.age-o.age:num; Age is a secondary condition *}*/*@Override* Public intCompareTo (person O) {//Sort by the length of the name*intnum = This. Name.length ()-o.name.length ();//length as the main condition*intnum2 = num = = 0? This. Name.compareto (o.name): num;//the content of the name as a secondary condition*returnNum2 = = 0? This. age-o.age:num2;//Age as secondary secondary condition* }    *}    * 2. Compare with comparator: Comparator,compare* Treeset<string> ts =NewTreeset<> (NewComparator<string> () {//defines the comparer (new Comparator () {} is a subclass object of Comparator)*@Override* Public intCompare (string s1, string s2) {//overriding the Compare method*intnum = S1.compareto (s2);//Compare Content*returnnum = = 0? 1:num;//If the content returns a number that is not 0*        }    *    });
* TreeSet stores integer type elements and traverses     new treeset<>();     * Ts.add (5);     * Ts.add (8);     * Ts.add (3);     * Ts.add (4);     * SYSTEM.OUT.PRINTLN (TS); // 3,4,5,8

6.TreeSet principle

* 1. Features
* TreeSet is used for sorting, you can specify an order, the object, the deposit will be arranged in the order specified
* 2. How to use
* A. Natural order (comparable)
* The Add () method of the TreeSet class promotes the stored object to the comparable type
* The CompareTo () method of the calling object and the object comparison in the collection
* Stored according to the results returned by the CompareTo () method
* B. Comparator order (Comparator)
* When creating a treeset, you can make a comparator
* If a subclass of comparator object is passed in, then TreeSet will be sorted in the order of the comparator
* The Add () method internally automatically calls the comparator interface to sort the compare () method
* C. Two different ways to differentiate
* TreeSet constructors do not pass, default according to the order of comparable in the class (no error ClassCastException) (Type conversion exception)
* TreeSet if incoming comparator, the priority is to follow comparator.

7. Note:

* 1. List*A. Normal for loop, using get ()*B. Call the iterator () method to get iterator, using the Hasnext () and Next () methods*c. Enhance for loop, as long as the class that can use iterator can be used*the D.vector collection can use the enumeration hasmoreelements () and Nextelement () methods* 2. Set*A. Call the iterator () method to get iterator, using the Hasnext () and Next () methods*B. Enhance the For loop, as long as the class that can use iterator can be used* 3. Normal for loop, iterator, enhanced for loop can be removed during traversal* Normal for loop: can delete element, but index to---* for(inti = 0; I < list.size (); i++) {        *if(List.get (i). Equals ("B")) {        * List.remove (i--);//the normal for loop can be deleted, but the index is i--, the index is not--the adjacent element is the same, can only delete the previous, cannot delete the back,*    }        * }     *iterators: You cannot use the Delete method of a collection, or a concurrent modification exception occurs, but you can use the Delete method of the iterator. * Enhanced for loop: Can not delete, will be out of concurrency modification exception.

Hashse, Linkedhashset, TreeSet (Java Basics 17)

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.