java--(iii) collection set set, HashSet class

Source: Internet
Author: User
Tags set set

------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------

First, set set

The set collection does not allow the same elements to be included, and if an attempt is made to add two identical elements to the same set set, the

The operation failed, the Add method returns False, and the new element is not added.

Set determines that two objects are the same, not using the = = operator, but according to the Equals method. In other words, as long as two objects

The Equals method will not accept the two objects if they are returned true,ser, whereas two objects are compared with the Equals method.

Returning False,set will accept both objects (even if the two objects are the same object, set can also treat them as two pairs

Like to come out). The following is an example program that uses normal set.

1 ImportJava.util.HashSet;2 ImportJava.util.Set;3 4 5  Public classSettest {6 7      Public Static voidMain (string[] args) {8Set names =NewHashset<>();9         //Add a String objectTenNames.add (NewString ("Jinan Snow")); One         //add a String object again A         //because two string objects compare equality through the Equals method -         //so add failed, return false -         BooleanReasult = Names.add (NewString ("Jinan Snow")); the         //See the collection with only one element from the output below -System.out.println (Reasult + "-+" +names); -     } -  +}

Operation Result:

false-->[and snow]

As can be seen from the above program, the names collection two times the added string object is obviously not the same object (because the two

Using the new keyword to create a string object), these two string objects use the = = operator to determine the positive return false, but by

The Equals method comparison returns true, so the addition fails. The final result outputs only one element.

1.HashSet class

HashSet is a typical implementation of the set interface, and most of the time using a set set is the implementation class. HashSet by Hash

Algorithm to store the elements in the collection, so it has good access and lookup performance.

HashSet has the following characteristics:

1) There is no guarantee that the order of the elements will be sorted, and the sequence may vary.

2) HashSet is not synchronous, if multithreading simultaneously accesses a hashset, assume that there are two or more threads at the same time

When you modify a HashSet collection, you must use code to ensure that it is synchronized.

3) The collection element value can be null.

The HashSet set determines that more than two equal criteria are two objects that are compared by equals () methods, and that two objects have a

The return value of the Hashcode () method is also equal.

The following program provides three classes A, B, and C, each of which overrides one or all of the two methods of Equals (), Hashcode ()

, this program allows you to see the same criteria that HashSet judge the set elements.

1 ImportJava.util.HashSet;2 3 4  Public classHashsettest {5     //the Equals method of Class A always returns true, but does not override the Hashcode method6     Static classA {7 @Override8          Public Booleanequals (Object o) {9             return true;Ten         } One     } A     //hashcode of Class B always returns 1, but does not override the Equals method -     Static classB { - @Override the          Public inthashcode () { -             return1; -         } -     } +     //Class C overrides the Hashcode method and the Equals method -     Static classC { + @Override A          Public inthashcode () { at             return2; -         } - @Override -          Public Booleanequals (Object obj) { -             return true; -         } in     } -  to      Public Static voidMain (string[] args) { +  -HashSet names =NewHashset<>(); theNames.add (NewA ()); *Names.add (NewA ()); $Names.add (NewB ());Panax NotoginsengNames.add (NewB ()); -Names.add (NewC ()); theNames.add (NewC ()); +          A System.out.println (names); the     } +  -}

Operation Result:

[Email protected], [email protected], [email protected], [email protected], [email protected]]

As can be seen from the above program, even though two a objects are returned true by the Equals () method, HashSet still treats them as

Two objects; even though the hashcode () of two B objects returns the same value (all 1), HashSet still treats them as the same

Object.

Attention:

When putting an object into HashSet, if you need to override the Equals () method of the corresponding class of the method, you should also override the

Hashcode () method. The rule is: if two objects are compared by the Equals () method to return True, the hashcode of the two objects

() values should also be the same.

Basic rules for overriding the Hashcode () method:

1) in a program run, multiple calls to the Hashcode () method on the same object should return the same value.

2) When two objects return true through the Equals () method, the Hashcode () method of the two objects should return an equal value.

3) The filed that are used as the Equals () method in the object should be computed with the hashcode value.

Hashcode the calculation of the return value:

return F1.hashcode () + (int) F2;

In order to avoid the incidental equivalence of direct addition (two objects F1, F2field are not equal, but their and exactly equal),

You can add a field by multiplying it by any number of primes.

return F1.hashcode () * + (int) F2 * 13;

If you add a Mutable object to HashSet, the field that modifies the Mutable object appears later, which can cause

It is the same as other elements in the collection (that is, two objects are compared by the Equals () method to return true, two objects

Hashcode () values are also equal). This could lead to the inclusion of two identical objects in a hashset. The following procedure demonstrates the

situation.

1 ImportJava.util.HashSet;2 ImportJava.util.Iterator;3 4 classR {5     intcount;6      PublicRintcount) {7          This. Count =count;8     }9 @OverrideTen      PublicString toString () { One          A         return"R[count:" + Count + "]"; -     } - @Override the      Public Booleanequals (Object obj) { -          -         if( This==obj) { -             return true; +         } -         if(obj! =NULL&& Obj.getclass () = = R.class) { +R r =(R) obj; A             if(R.count = = This. Count) { at                 return true; -             } -         } -         return false; -     } - @Override in      Public inthashcode () { -          to         return  This. Count; +     } - } the  Public classHashSetTest2 { *  $      Public Static voidMain (string[] args) {Panax Notoginseng  -HashSet HS =NewHashset<>(); theHs.add (NewR (5)); +Hs.add (NewR (-3)); AHs.add (NewR (9)); theHs.add (NewR (-2)); +         //Print HashSet collection, collection not duplicated - System.out.println (HS); $         //Take the first element out of the $Iterator it =hs.iterator (); -R first =(R) It.next (); -         //assign a value to the count instance variable for the first element theFirst.count =-3; -         //output HashSet Collection again, the collection element has repeating elementsWuyi System.out.println (HS); the         //Delete R object with Count 3 -Hs.remove (NewR (-3)); Wu System.out.println (HS); -System.out.println ("HS is the R object with a count of-3?") "+ Hs.contains (NewR (-3))); AboutSystem.out.println ("HS is the R object with a package count of 5?") "+ Hs.contains (NewR (5))); $System.out.println ("HS is the R object with a package count of 9?") "+ Hs.contains (NewR (9))); -     } -  -}

Operation Result:

[R[count:5], R[count:9], r[count:-3], r[count:-2]][r[count:-3], R[count:9], r[count:-3], r[count:-2]][R [Count:-3], R[count:9], r[count:-2]]hs is the R object with a package count of-3? false HS is the R object with a package count of 5?  falseHS whether the package count is 9 R object?  True

First.count in the above program =-3; Because the count instance variable of the first R object in the HashSet collection was changed

Value, which causes the R object to be the same as other objects in the collection. When you try to delete the R object of Count =-3, the HashSet

The hashcode value of the object is computed to find out where the object is saved in the collection, and then the object here is associated with the count

The R object for-3 is compared with the Equals () method, and if it is equal, the object--hashset only the third element

satisfies the condition (the first element is actually saved in the position corresponding to the R object of Count 5), so the third element is deleted

。 As for the first R object with Count 3, he remains at the position corresponding to the R object of Count 5, but with the Equals () method

Compare it to the R object with Count 5 to return false--this will cause HashSet to not be able to access the element accurately.

  

java--(iii) collection set set, HashSet class

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.