HashMap概述
一、HashMap是 Map 接口使用频率最高的实现类。
二、允许使用null键和null值,与HashSet一样,不保证映射的顺序。
三、HashMap 判断两个 key 相等的标准是:两个 key 通过 equals() 方法返回 true,hashCode 值也相等。
四、HashMap 判断两个 value相等的标准是:两个 value 通过 equals() 方法返回 true。
常用方法和遍历的实现代码
@Test
public void test() {
Map map = new HashMap();
map.put("AA", 33);
map.put("BB", 323);
map.put("CC", 313);
map.put("DD", 333);
map.put(123, "kk");
map.put(new Person(11, "zhao"), 55);
// 1、遍历key值
Set set = map.keySet();
for (Object o : set) {
System.out.println(o);
}
// 2、遍历Value
Collection collection = map.values();
Iterator i = collection.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
// 遍历键值对
// 方式一:
Set set1 = map.keySet();
for (Object o : set1) {
System.out.println(o + "-" + map.get(o));
}
// 方式二:
Set set2 = map.keySet();
for (Object o : set2) {
Map.Entry entry = (Map.Entry) o;
System.out.println(entry.getKey() + " " + entry.getValue());
}
}