Map用 put(k,v) / get(k),还可以使用containsKey()/containsValue()来检查其中是否含有某个key/value。
HashMap会利用对象的hashCode来快速找到key。
* hashing
哈希码就是将对象的信息经过一些转变形成一个独一无二的int值,这个值存储在一个array中。
我们都知道所有存储结构中,array查找速度是最快的。所以,可以加速查找。
发生碰撞时,让array指向多个values。即,数组每个位置上又生成一个梿表。
/**
* 1.加入元素 2.遍历这个map 3.移除元素
*
* @author Administrator
*
*/
public class HashMapDemo {
public static void main(String args[]) {
HashMap<String, Object> hm = new HashMap<String, Object>();
People p1 = new People();
People p2 = new People();
People p3 = new People();
People p4 = new People();
hm.put("People3", p1);
hm.put("People1", p2);
hm.put("People4", p3);
hm.put("People2", p4);
Iterator<String> it = hm.keySet().iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
class People {
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}