定义:HashMap中每一个键只能映射一个键,当有重复的键的时候不会重复创建新的映射关系;而是使用先前的key。
实例代码1
package Test_10;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Test {
public void testHashMap(){
Map<String,String> hashMap = new HashMap<String, String>();
hashMap.put("aaa", "111");
hashMap.put("aaa", "222");
Iterator iterator = hashMap.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry entry = (Map.Entry) iterator.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println(key+":"+value);
}
}
public static void main(String[] args){
Test t1 = new Test();
t1.testHashMap();
}
}
运行结果:
aaa:222
对象作为key
package Test_10;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* 对象作为key
* @author msi
*
*/
class Person{
String id;
String name;
public Person(String id,String name){
this.id = id;
this.name = name;
}
public String toString(){
return "id="+id+",name"+name;
}
}
public class Test {
public void testHashMap(){
Map<Person,String> hashMap = new HashMap<Person, String>();
Person p1 = new Person("111","name1");
Person p2 = new Person("111","name1");
hashMap.put(p1, "I am person1");
hashMap.put(p2, "I am person2");
Iterator iterator = hashMap.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Person, String> entry =(Map.Entry<Person, String>)iterator.next();
Person key= entry.getKey();
String value = entry.getValue();
System.out.println(key+":"+value);
}
}
public static void main(String[] args){
Test t1 = new Test();
t1.testHashMap();
}
}
运行结果:
id=111,namename1:I am person1
id=111,namename1:I am person2
HashMap中的put函数:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}