Yesterday, in the Java bar of Baidu saw someone asked about HashSet problem. Here's the code he posted:
1 ImportJava.util.HashSet;2 3 Public classjavatest4 {5 Public Static voidMain (string[] args)6 {7hashset<person> HS =NewHashset<person>();8Person p =NewPerson ("Zhang San", 21);9 Hs.add (p);TenP.setname ("John Doe"); OneP.setage (22); A Hs.add (p); - System.out.println (HS); - } the } - - class Person - { + PrivateString name; - Private intAge ; + APerson (String name,intAge ) at { - This. Name =name; - This. Age =Age ; - } - - PublicString getName () in { - returnname; to } + - Public voidsetName (String name) the { * This. Name =name; $ }Panax Notoginseng - Public intgetage () the { + returnAge ; A } the + Public voidSetage (intAge ) - { $ This. Age =Age ; $ } - - Public inthashcode () the { - returnName.hashcode () + age * 21;Wuyi } the - Public Booleanequals (Object obj) Wu { - if(objinstanceofPerson ) About { $Person p =(person) obj; - returnName.equals (P.getname ()) && age = =p.getage (); - } - Else A { + return false; the } - } $ the PublicString toString () the { the returnName + "--" +Age ; the } -}
Output Result:
[John Doe--22, John Doe--22]
The landlord does not understand why the HashSet in the two elements are the same. It's not a good deal. Cannot duplicate elements in Set?
I am confident that HashSet is still familiar (although not the source code), hurriedly wrote a reply, the results have not been mentioned in the point.
Later, the landlord changed the Equals method and test function:
ImportJava.util.HashSet; Public classjavatest{ Public Static voidMain (string[] args) {HashSet<Person> HS =NewHashset<person>(); Person P=NewPerson ("Zhang San", 21); Hs.add (P); P.setname ("John Doe"); P.setage (22); Hs.add (P); Hs.add (NewPerson ("John Doe", 22)); Hs.add (NewPerson ("Zhang San", 21)); SYSTEM.OUT.PRINTLN (HS); }}classperson{PrivateString name; Private intAge ; Person (String name,intAge ) { This. Name =name; This. Age =Age ; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } Public inthashcode () {returnName.hashcode () + age * 21; } Public Booleanequals (Object obj) {//increased judgment on whether the same object if( This==obj) { return true; } if(objinstanceofPerson ) {Person P=(person) obj; returnName.equals (P.getname ()) && age = =P.getage (); } Else { return false; } } PublicString toString () {returnName + "--" +Age ; }}
The output is:
[John Doe--22, John Doe--22, Zhang San--21]
If you understand the HashSet principle, the above results are not difficult to explain.
Let's see, it's interesting, I think there is some help to understand HashSet.
An interesting Java HashSet problem