Java in HashSet detailed

Source: Internet
Author: User

The realization of HashSet

For HashSet, it is based on HASHMAP implementation, HashSet the bottom of the HashMap to save all the elements, so HashSet implementation is relatively simple, view the source code of HashSet, you can see the following code:

Java code
  1. Public class Hashset<e>
  2. extends Abstractset<e>
  3. implements Set<e>, cloneable, Java.io.Serializable
  4. {
  5. //Use HashMap key to save all elements in HashSet
  6. private transient hashmap<e,object> map;
  7. //Define a dummy object as the value of HashMap
  8. private Static final Object PRESENT = new Object ();
  9. ...
  10. //Initialize HashSet, the underlying initializes a HashMap
  11. Public HashSet ()
  12. {
  13. Map = new hashmap<e,object> ();
  14. }
  15. //Create HashSet with the specified initialcapacity, Loadfactor
  16. //actually is to create the HASHMAP with corresponding parameters
  17. Public HashSet (int initialcapacity, float loadfactor)
  18. {
  19. Map = New Hashmap<e,object> (initialcapacity, loadfactor);
  20. }
  21. Public HashSet (int initialcapacity)
  22. {
  23. Map = new hashmap<e,object> (initialcapacity);
  24. }
  25. HashSet (int initialcapacity, float loadfactor, boolean dummy)
  26. {
  27. Map = new linkedhashmap<e,object> (initialcapacity
  28. , Loadfactor);
  29. }
  30. //Call map's keySet to return all keys
  31. Public iterator<e> Iterator ()
  32. {
  33. return Map.keyset (). iterator ();
  34. }
  35. ///Call HashMap the size () method returns the number of Entry, and the number of elements in the Set
  36. public int size ()
  37. {
  38. return map.size ();
  39. }
  40. //Call HashMap's IsEmpty () to determine if the HashSet is empty,
  41. //When the HashMap is empty, the corresponding HashSet is also empty
  42. Public Boolean isEmpty ()
  43. {
  44. return Map.isempty ();
  45. }
  46. //Call HashMap ContainsKey to determine if the specified key is included
  47. all the elements of//hashset are saved by the HASHMAP key .
  48. Public Boolean contains (Object o)
  49. {
  50. return Map.containskey (o);
  51. }
  52. //Put the specified element in HashSet, that is, put the element as a key HashMap
  53. Public Boolean add (E e)
  54. {
  55. return Map.put (E, PRESENT) = = null;
  56. }
  57. //Call the HashMap Remove method to delete the specified Entry, and then delete the corresponding element in the HashSet
  58. Public boolean remove (Object o)
  59. {
  60. return Map.Remove (o) ==present;
  61. }
  62. //The Clear method of calling Map clears all Entry and clears all elements in HashSet
  63. public void Clear ()
  64. {
  65. Map.clear ();
  66. }
  67. ...
  68. }



As can be seen from the above source program, the implementation of HashSet is very simple, it just encapsulates a HashMap object to store all the collection elements, all the collection elements put into HashSet are actually saved by the key of HashMap, while the HASHMAP value is stored A PRESENT, which is a static object.

Most of the methods of HashSet are implemented by invoking the HashMap method, so HashSet and HashMap two sets are essentially the same in their implementations.
After mastering the above theoretical knowledge, take a look at an example program and test whether you really mastered the functions of the HashMap and HashSet collections.
Java code
  1. class Name
  2. {
  3. private String first;
  4. private String last;
  5. Public Name (string First, string last)
  6. {
  7. This.first = First;
  8. this.last = last;
  9. }
  10. public Boolean equals (Object o)
  11. {
  12. if (this= = O)
  13. {
  14. return true;
  15. }
  16. if (o.getclass () = = Name. Class)
  17. {
  18. Name n = (name) o;
  19. return N.first.equals (first)
  20. && n.last.equals (last);
  21. }
  22. return false;
  23. }
  24. }
  25. Public class Hashsettest
  26. {
  27. public static void Main (string[] args)
  28. {
  29. set<name> s = new hashset<name> ();
  30. S.add (new Name ("abc", "123"));
  31. System.out.println (
  32. S.contains (new Name ("abc", "123")));
  33. }
  34. }



After adding a new name ("abc", "123") object to HashSet in the above program, it is immediately determined by the program that the HashSet contains a new name ("abc", "123") object. Coarse looks, it is easy to assume that the program will output true.

Actually running the above program will see the program output false, this is because HashSet judge two objects equal to the standard in addition to the Equals () method is required to return true, but also requires two objects hashcode () return values equal. The above program does not override the name class's Hashcode () method, the Hashcode () return value of the two name objects is not the same, so HashSet treats them as 2 objects, so the program returns FALSE.

Thus, it is important to override the Equals (Object obj) method and the Hashcode () method of this class when we try to treat the object of a class as a HashMap key, or try to save the object of this class in HashSet. And the return values of the two methods must be consistent: when the two hashcode () return values of the class are identical, they should also return true through the Equals () method. In general, all key attributes that participate in the calculation of the hashcode () return value should be used as the criteria for the Equals () comparison.
The following program correctly rewrites the hashcode () and Equals () methods of the Name class, with the following procedures:
Java code
  1. Class Name
  2. {
  3. private String first;
  4. private String last;
  5. Public Name (string First, string last)
  6. {
  7. This.first = First;
  8. this.last = last;
  9. }
  10. //Determine if two Name is equal according to first
  11. public Boolean equals (Object o)
  12. {
  13. if (this= = O)
  14. {
  15. return true;
  16. }
  17. if (o.getclass () = = Name. Class)
  18. {
  19. Name n = (name) o;
  20. return n.first.equals (first);
  21. }
  22. return false;
  23. }
  24. //Hashcode () return value of Name object based on first calculation
  25. public int hashcode ()
  26. {
  27. return First.hashcode ();
  28. }
  29. Public String toString ()
  30. {
  31. return "name[first=" + First + ", last=" + Last + "]";
  32. }
  33. }
  34. public class HashSetTest2
  35. {
  36. public static void Main (string[] args)
  37. {
  38. hashset<name> set = new hashset<name> ();
  39. Set.add (new Name ("abc", "123"));
  40. Set.add (new Name ("abc", "456"));
  41. SYSTEM.OUT.PRINTLN (set);
  42. }
  43. }


The above program provides a name class that overrides the Equals () and toString () two methods, both of which are judged by the first instance variable of the name class, and when the first instance variable of the two name object is equal, the two N The Hashcode () return value of the Ame object is also the same, and true is also returned by the Equals () comparison.

The main method of the program first adds the first name object to the HashSet, the name object is named "ABC", and then the program tries again to add a Name object "ABC" to the HashSet, it is clear that the new Na The Me object is added to the HashSet because the first of the name object you are trying to add is also "ABC", and HashSet will determine that the new name object here is the same as the original name object and therefore cannot be added, and the program will look at the output set collection at ① code. To the collection contains only one name object, which is the first name object that is "123".

Java in HashSet detailed

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.