Java Collection 2

Source: Internet
Author: User

these days to see the next HashSet and HashMap, talk about my understanding, if there is a mistake, please point out the correction, thank you!


1.1 HashSet

1.11 hashset is a collection class that implements the set interface, with the following characteristics:

(1) The order in which elements are returned is not guaranteed when traversing elements

(2) Duplicate elements are not allowed, where the "repeating" element means that two objects have the same hash code and return true when compared with the Equals () method

(3) Allow empty elements to be included

(4) The bottom is a hash table


1.12 The principle of hashset storage elements

The above is a description of HashSet in Java advanced programming.

(When you add an object in set, use the hash code of the object to select the "bucket" for the object to be placed.) Unequal objects may have different hash codes but are still in the same bucket, and two objects judged equal are always in the same bucket. This is extremely important because when you determine whether a specified object is contained in a set, the hash code of the object is used to determine the bucket in which the object resides, and the object in that bucket is traversed by using the Equals () method to determine whether the bucket already contains the object. In other words, use the Hashcode () method to specify the object sub-collection (bucket) in which the object resides, and then check the subset by Equals () to determine whether the specified object is found. )


According to my understanding, I use the following words to describe, I hope I understand that there is no error

When adding an element to HashSet, the Hashcode method of the element is called to get the hash code value of the object, and the value calculates the position in the hash table where the element resides.

(1) If the calculated position does not have any value, then the element can be added to the hash table

(2) If another element already exists at that location, the call to the Equlas () method is compared to the element at that location, and if it returns false, it is added.


Let's say that there are several situations where you try to rewrite Hashcode and Equlas ()     

1.hashCode is the same and equals () returns to True

Public class hashsetdemo {public static void main (String[] args)  { Hashset<person> set=new hashset (); Person p1=new person (20,  "Xiao Han",  20); Person p2=new person (20,  "Xiao Han",  20); Set.add (p1); Set.add (p2); System.out.println ("p1 hashcode=" +p1.hashcode () + "    " + "p2 hashcode=" + P2.hashcode ()); System.out.println ("size=" +set.size () +  "  set=" +set);}} class person {private int id;private string name;private int age; Public person (int id,string name, int age)  {this.id=id;this.name =  Name;this.age = age;} @Overridepublic  int hashcode ()  {return id;} @Overridepublic  boolean equals (object obj)  {person p= (person)  obj;return  Name.equals (P.name)  && age==p.age;} @Overridepublic  string tostring () {return  "ID= "+id+"  name= "+name+"  age= "+age;}} Output is:            p1 hashcode=20     p2 hashcode=20            size= 1set=[id=20 name= Xiao Han  age=20]


2.hashCode same but Equals () returns false

Hashset<person> set=new HashSet (); Person P1=new person (20, "Xiao Han", 20); Person P2=new person (20, "Lulu"), Set.add (p1); Set.add (p2); System.out.println ("P1 hashcode=" +p1.hashcode () + "" + "P2 hashcode=" +p2.hashcode ()); System.out.println ("size=" +set.size () + "set=" +set); output: P1 hashcode=20 p2 hashcode=20 size=2 set=[id =20 name= age=20, id=20 name= Xiao Han age=20]

As we can see from the above results, when hashcode () is the same, the Equlas () method is called to compare elements to determine whether to add the elements


1.2 HashMap

Set is a collection of objects, and map is not only a collection of objects, but each object has a corresponding value. That is, the map (map) represents a set of key-value pairs, which are the elements in the collection. Where HashMap is a class that implements the map interface, with the following characteristics:

(1) thread is unsafe, access speed is fast. The underlying is implemented as a hash table .

(2) key does not allow repeating elements, and value can be repeated

Hashmap<intger,person> map=new hashmap<intger,person> ();    Person P1=new person (1, "Xiao Han", 20);    Person P2=new person (1, "Little Dew", 20);    Map.put (1,P1); Map.put (2,P1);

Person P=map.get (3);

This line of code looks for the key 3 in the map, returns the corresponding person object if there is one, and returns null if none. This lookup of objects is extremely useful, and unlike list lookups, finding objects by key in map does not need to traverse the key table in the map. Instead, use the hashcode of the key to locate the hash table where the value resides, so that even a very large map collection can be quickly searched.


The following code is a few ways to traverse HashMap

Map<string,string> map=new hashmap<string,string> () map.put ("A", "AA"), Map.put ("B", "BB"), Map.put ("C", "CC");//The first type of EntrySet () returns a Set view of the mappings contained in this map. For (entry<string, String>entry:map.entryset ()) {System.out.println ("key=" +entry.getkey () + "value=" + Entry.getvalue ());} System.out.println ("=========== Gorgeous split line ===============");//The second KeySet returns a Set view of the keys contained in this map. For (String S:map.keyset ()) {System.out.println ("key=" +s+ "value=" +map.get (s));} System.out.println ("=========== Gorgeous split line ===============");//The third value returns a Collection view of the values contained in this map. For (String s:map.values ()) {System.out.println ("value=" +s);}



Java Collection 2

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.