The first season of Java HashSet Storing custom object issues and considerations

Source: Internet
Author: User

Previous article http://blog.csdn.net/qq_32059827/article/details/51578158

Write to the storage string type when there is a disorder, and this disorder is not random disorder, it is a certain storage law. The last time you stored a string, here's a look at whether storing custom objects is the same rule. In fact, there are a lot of questions to discuss.

The custom object is stored and the code is written out:

Import Java.util.hashset;public class HashSetDemo2 {public static void main (string[] args) {//Create collection Object hashset<student& Gt HS = new hashset<student> ();//Create student object Student S1 = new Student ("Brigitte", 27); Student s2 = new Student ("spokesperson", 22); Student s3 = new Student ("condom", 30); Student S4 = new Student ("Brigitte", 27); Student S5 = new Student ("Brigitte", 20); Student s6 = new Student ("Fan Bingbing", 22);//add Element Hs.add (S1); Hs.add (S2); Hs.add (S3); Hs.add (S4); Hs.add (S5); Hs.add (S6);// Traverse collection for (Student s:hs) {System.out.println (S.getname () + "---" + s.getage ());}}
Here is the Student class:

Package cn.itcast_02;/** * @author Administrator *  */public class Student {private String name;private int age;public Student () {super ();} Public Student (String name, int.) {super (); this.name = Name;this.age = age;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}}
We suspect that the results of the operation should be non-repetitive, that is, the guess result should be:

Brigitte---20
Spokesperson---22
Fan Bingbing---22
Brigitte---27
Condom---30
That is, Brigitte--27 does not appear duplicated. Console actual output:

Brigitte---20
Spokesperson---22
Fan Bingbing---22
Brigitte---27
Condom---30
Brigitte---27

Obviously, we were wrong! And why does the string have to be duplicated? What is the reason for this?

The explanations are as follows:

By looking at the source of the Add method, we know that this method relies on two methods: Hashcode () and Equals ().

If the class does not override both methods, the object () is used by default. In general, only hashcode may not be the same, and equals is not the same; they are all added to the collection.
* For example, custom objects are printed out without overriding the hashcode () and Equals () methods. This is also the reason for not repeating.
* While the string class (when writing a string object) overrides the Hashcode () and Equals () methods, it is possible to remove the same string as the content. Only one left.


So we're going to modify the code inside the student class to add hashcode () and Equals (). Automatically generated!


Package cn.itcast_02;/** * @author Administrator * */public class Student {private String name;private int age;public Stu Dent () {super ();} Public Student (String name, int.) {super (); this.name = Name;this.age = age;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} @Overridepublic int hashcode () {final int prime = 31;int result = 1;result = Prime * result + Age;result = Prime * result + ((name = = null)? 0:name.hashcode ()); return result;} @Overridepublic boolean equals (Object obj) {System.out.println (this + "---" + obj), if (this = = obj) return true;if (obj = = NULL) return False;if (GetClass ()! = Obj.getclass ()) return false; Student other = (Student) obj;if (age! = other.age) return false;if (name = = null) {if (other.name! = null) return false;} E LSE if (!name.equals (other.name)) return False;return true;}}
No duplicates are printed at this time:

Condom---30
Fan Bingbing---22
Spokesperson---22
Brigitte---27
Brigitte---20

The next article uses a graph to explain the bucket structure and hashset storage details.


The first season of Java HashSet Storing custom object issues and considerations

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.