最近做一个小项目用到了HashMap,一头雾水,说明自己的基础知识真的很不扎实。从网上查资料整理了两种常用的遍历HashMap的方法:
import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.Map.Entry;
public class HashMapTest { public static void main(String args[]) { HashMap<String, Object> hash = new HashMap<String, Object>(); Person p1 = new Person("张三", 20); Person p2 = new Person("李四", 21); hash.put("p1", p1); hash.put("p2", p2); ArrayList<String> a = new ArrayList<String>(); a.add("jia"); a.add("hello"); hash.put("a", a);
//方法一:遍历key System.out.println("---------------遍历Key--------------"); Iterator it1 = hash.keySet().iterator();
while (it1.hasNext()) { Object key = it1.next(); Object val = hash.get(key); System.out.println("key: " + key + "/tval: " + val); }
//方法二:遍历key和value封装的实体 System.out.println("----------遍历Key和Value封装的实体--------"); Iterator it2 = hash.entrySet().iterator();
while (it2.hasNext()) { Entry entry = (Entry) it2.next(); Object key = entry.getKey(); Object val = entry.getValue(); if (key.equals("p1")) entry.setValue("bye"); System.out.println("key: " + key + "/tval: " + val); } }}
//Person类
class Person { String name; int age;
public Person(String name, int age) { this.name = name; this.age = age; }
public String toString() { return name + " " + age; }}
运行结果:
---------------遍历Key--------------key: p1 val: 张三 20key: a val: [jia, hello]key: p2 val: 李四 21----------遍历Key和Value封装的实体--------key: p1 val: 张三 20key: a val: [jia, hello]key: p2 val: 李四 21
