Hashmap -- traverse ---- keyset -- entryset

Source: Internet
Author: User

 

Import Java. util. *; import Java. util. map. entry; class person implements comparable <person> {public string name; Public int age; Public Person (string name, int age) {This. name = Name; this. age = age;} Public String getname () {return name;} public int getage () {return age;} @ overridepublic int hashcode () {return name. hashcode () + age ;}@ overridepublic Boolean equals (Object OBJ) {If (! (OBJ instanceof person) throw new classcastexception ("inconsistent types"); person = (person) OBJ; return this. name. equals (person. name) & (this. age = person. age) ;}@ overridepublic int compareto (person p) {int num = (New INTEGER (AGE )). compareto (New INTEGER (P. age); If (num = 0) return name. compareto (P. name); Return num ;}@ overridepublic string tostring () {return name + ":" + age ;}} public class maptest {public static void main (string ARGs []) {hashmap <person, string> hashmap = new hashmap <person, string> (); hashmap. put (new person ("boy", 20), "Jiangsu"); hashmap. put (new person ("girl", 19), "Henan"); hashmap. put (new person ("person", 49), "China"); // The following output uses the keyset method set <person> keyset = hashmap. keyset (); For (iterator <person> it = keyset. iterator (); it. hasnext ();) {person P = it. next (); system. out. println (P. getname () + ":" + P. getage () + ":" + hashmap. get (p);} // use the entryset method set <entry <person, string> entryset = hashmap. entryset (); For (iterator <entry <person, string> it = entryset. iterator (); it. hasnext ();) {entry <person, string> item = it. next (); system. out. println (item. getkey () + ":" + item. getvalue () ;}}2011/10/28 14:27:45

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.