1. Case of HashMap Collection (hashmap<student,string>)
Hashmap<student,string>
Key: Student
Requirement: If the member variable values for two objects are the same, then the same object.
Value: String
HashMap is the most commonly used map collection, and its key-value pairs are stored with the hash code of the key to determine where the value is placed.
An object that is a key in HashMap must override the Hashcode () method of object and the Equals () method
2. code example:
(1)Student. Java, as follows:
1 Packagecn.itcast_02;2 3 Public classStudent {4 PrivateString name;5 Private intAge ;6 7 PublicStudent () {8 Super();9 }Ten One PublicStudent (String name,intAge ) { A Super(); - This. Name =name; - This. Age =Age ; the } - - PublicString GetName () { - returnname; + } - + Public voidsetName (String name) { A This. Name =name; at } - - Public intGetage () { - returnAge ; - } - in Public voidSetage (intAge ) { - This. Age =Age ; to } + - @Override the Public inthashcode () { * Final intPrime = 31; $ intresult = 1;Panax Notoginsengresult = Prime * result +Age ; -result = Prime * result + ((name = =NULL) ? 0: Name.hashcode ()); the returnresult; + } A the @Override + Public Booleanequals (Object obj) { - if( This==obj) $ return true; $ if(obj = =NULL) - return false; - if(GetClass ()! =Obj.getclass ()) the return false; -Student other =(Student) obj;Wuyi if(Age! =other.age) the return false; - if(Name = =NULL) { Wu if(Other.name! =NULL) - return false; About}Else if(!name.equals (other.name)) $ return false; - return true; - } - A}
(2) test class HashMapDemo4, as follows:
1 Packagecn.itcast_02;2 3 ImportJava.util.HashMap;4 ImportJava.util.Set;5 6 /*7 * hashmap<student,string>8 * Key: Student9 * Requirements: If the member variable values for two objects are the same, then the same object . Ten * Value: String One */ A Public classHashMapDemo4 { - Public Static voidMain (string[] args) { - //To create a collection object theHashmap<student, string> HM =NewHashmap<student, string>(); - - //Create student Objects -Student S1 =NewStudent ("Marten Cicada", 27); +Student s2 =NewStudent ("Wang Zhaojun", 30); -Student s3 =NewStudent ("Xi Shi", 33); +Student S4 =NewStudent ("Yang Yuhuan", 35); AStudent S5 =NewStudent ("Marten Cicada", 27); at - //adding elements -Hm.put (S1, "8888"); -Hm.put (S2, "6666"); -Hm.put (S3, "5555"); -Hm.put (S4, "7777"); inHm.put (S5, "9999"); - to //Traverse +Set<student> set =Hm.keyset (); - for(Student key:set) { theString value =Hm.get (key); *System.out.println (Key.getname () + "---" + key.getage () + "---" $+value);Panax Notoginseng } - } the}
Run the results as follows:
Student as the key object, overriding object's Hashcode () method and the Equals () method, (code as above), rerun the result as follows :
Java Basic Knowledge Hardening Collection Framework note 57:map Collection HashMap collection (hashmap<student,string>) case