Java Learning Note 31 (Set Framework V: Introduction to set interface, hash table)

Source: Internet
Author: User

Features of the SET interface:

1. Does not contain duplicate elements

2.set collections are not indexed and can only be traversed with iterators or enhanced for loops

The bottom of the 3.set is the map collection

The method is basically the same as the collection method.

The implementation class of the set interface is HashSet:

1. Unordered collection

2. Can be stored empty (null)

3. Duplicate elements may not exist

Example:

 Packagedemo;ImportJava.util.HashSet;ImportJava.util.Iterator;ImportJava.util.Set; Public classHashsetdemo { Public Static voidMain (string[] args) {Set<String> set =NewHashset<string>(); Set.add ("ABC1"); Set.add ("ABC1"); Set.add ("ABC2"); Set.add ("ABC3"); Set.add ("ABC4"); Iterator<String> I1 =Set.iterator ();  while(I1.hasnext ()) {System.out.println (I1.next ()); }    }}/*Output: Note: The output features here are unordered ABC1ABC4ABC2ABC3*/

The set underlying data structure is a hash table:

Features: Fast storage removal

Principle: Specific omission, simply said to be linked list array binding body

The hash value of the object: a normal integer

Can be understood as a social security number, which is the basis for hashset storage

 Package demo;  Public class Person {}
 Packagedemo; Public classHashdemo { Public Static voidMain (string[] args) {person P=NewPerson (); inti =P.hashcode ();        System.out.println (i); //each run will output a different integer, such as 1191201656String S1=NewString ("ABC"); String S2=NewString ("ABC"); System.out.println (S1.hashcode ());//96354System.out.println (S2.hashcode ());//96354//here Stirng rewrite the Hashcode method, there is a corresponding calculation formula//when the contents of a string are the same, the result of the operation is the same, so the hash values of S1 and S2 are the same    }}

Hash table stored procedures:


1. Calling the object's hash value

2. The collection searches within the container for a duplicate hash value, if not, the new element is stored, the hash value is recorded

3. Store again, repeat the top process

4. If there is a duplicate hash value, call the latter's Equals method, the parameter is the caller, the result is true, the collection is judged to be a repeating element, not deposited

If the same string is stored, the hash value is the same, and the Equals method is true, it will not be stored in the same

As long as the hash value is the same or the Equals method is true, it will not be deposited, as long as one of them is not satisfied, it will be stored

Hash table stores Custom objects:

 Packagedemo; Public classPerson {PrivateString name; Private intAge ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString toString () {return  This. Name + ":" + This. Age; }     PublicPerson () {} PublicPerson (String name,intAge ) {        Super();  This. Name =name;  This. Age =Age ; }}

 Packagedemo;ImportJava.util.HashSet; Public classHashdemo { Public Static voidMain (string[] args) {HashSet<Person> Setperson =NewHashset<person>(); Setperson.add (NewPerson ("a", 17)); Setperson.add (NewPerson ("B", 20)); Setperson.add (NewPerson ("B", 20)); Setperson.add (NewPerson ("C", 18));        System.out.println (Setperson); //[C:18, B:20, A:17, b:20]//found a duplicate element was deposited//so find a way to treat the person object with the same name as age as the same object//so you need to rewrite the Hashcode method    }}

Rewrite yourself:

 Packagedemo; Public classPerson {PrivateString name; Private intAge ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString toString () {return  This. Name + ":" + This. Age; }     PublicPerson () {} PublicPerson (String name,intAge ) {        Super();  This. Name =name;  This. Age =Age ; }     Public inthashcode () {returnName.hashcode () +age*66; }     Public Booleanequals (Object obj) {if( This==obj) {            return true; }        if(obj = =NULL) {            return false; }        if(objinstanceofPerson ) {Person P=(person) obj; returnName.equals (p.name) && age = =P.age; }        return false; }}

Eclipse can help us write:

 Packagedemo; Public classPerson {PrivateString name; Private intAge ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString toString () {return  This. Name + ":" + This. Age; }     PublicPerson () {} PublicPerson (String name,intAge ) {        Super();  This. Name =name;  This. Age =Age ; } @Override Public inthashcode () {Final intPrime = 31; intresult = 1; Result= Prime * result +Age ; Result= Prime * result + ((name = =NULL) ? 0: Name.hashcode ()); returnresult; } @Override Public Booleanequals (Object obj) {if( This==obj)return true; if(obj = =NULL)            return false; if(GetClass ()! =Obj.getclass ())return false; person Other=(person) obj; if(Age! =other.age)return false; if(Name = =NULL) {            if(Other.name! =NULL)                return false; } Else if(!name.equals (other.name))return false; return true; }}

Linkedhashset collection: a hash table implementation based on a linked list, inheriting HashSet, which has a sequential

Example:

 Packagedemo;ImportJava.util.LinkedHashSet; Public classLinkedhashsetdemo { Public Static voidMain (string[] args) {//the ordered setlinkedhashset<integer> link =NewLinkedhashset<integer>(); Link.add (1); Link.add (2); Link.add (3); Link.add (4);        System.out.println (link); //[1, 2, 3, 4]    }}

Some questions about hashcode and equals are asked in the interview:

1. Two objects have the same hash value, does the Equals method always return true? Not necessarily

Depending on how to override Equals, if the override fixed it returns false, the result must be false

The 2.equals method returns True, so the hash value must be the same? Must

If a static variable is defined in the class (static int a = 1) and then overridden Hashcode returns A+1, then each object has a different hash value

However, Java stipulates that: objects are equal, must have the same hash code value, so here is a certain

Java Learning Note 31 (Set Framework V: Introduction to set interface, hash table)

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.