`

hashmap

阅读更多
HashMap的实例用来存放一对值,即一个称为key,一个称为value,比如你想存放这样一些信息:存储每一个国家的最高领导人的名字,你可以这样做:  
    HashMap   hs=new   HasMap();  
     hs.put("America","Bush");  
     hs.put("China","Hu");  
     其中America是关键字(key),Bush是值(value)。  
  这种数据结构对这样的值对的检索是非常方便的,比如说,你要查询美国的最高领导人的名字,你可以这样做:hs.get("America"),结果应该是Bush。
转载

package test;

import java.util.*;

class hashmap {
public static void main(String args[]) {
HashMap<String, String> hm = new HashMap<String, String>();
// store some Objects.
hm.put("Rajib Sarma", "100");
// duplicate keys are not allowed.
hm.put("Rajib Sarma", "200");// The value "100" is replaced by "200".
hm.put("Sazid Ahmed", "200");
// Display the contents of the HashMap
System.out.println("Displaying all the keys/values.\r\n");
System.out.println("Key\t\tValue\r\n");
// get all the keys
Collection<String> c = hm.keySet();
// obtain an Iterator
Iterator<String> i = c.iterator();
while (i.hasNext()) {
// obtain a key
Object key = i.next();
// obtain the value of the key
Object value = hm.get(key);
System.out.println(key + "\t" + value);
}//while ends
}//main ends
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics