value时可重复的,但无序的,用Collection来简称。
Entry: 键值对 对象。
在Map类设计是,提供了一个嵌套接口(static修饰的接口):Entry。Entry将键值对的对应关系封装成了对象,即键值对对象,这样我们在遍历Map集合时,就可以从每一个键值对(Entry)对象中获取对应的键与对应的值。
HashMap的实现原理 JDK7中
在JDK8中:
Map接口的方法:
package MapInterface;
import org.junit.Test;
import java.util.*;
public class MapMethod {
@Test
public void test1(){
Map map = new HashMap();
map.put("aa",123);
map.put("bb",456);
map.put("cc",789);
map.put("dd",101112);
System.out.println(map);
Map map1 = new HashMap();
// 修改
map1.put("cc",123);
map1.put("dd",123);
map.putAll(map1);
System.out.println(map);
// remove(Object key)
Object value = map.remove("cc");
System.out.println(value);
System.out.println(map);
// clear()清空map中的数据,与map=null 不同
map.clear();
System.out.println(map);
}
// 元素查询
@Test
public void test2(){
Map map = new HashMap();
map.put("aa",123);
map.put(123,"aa");
map.put("bb",456);
// get(key)
System.out.println(map.get(123));
// containisKey(key)
boolean isExist = map.containsKey("bb");
System.out.println(isExist);
// containisValue(value)
isExist = map.containsValue(123);
System.out.println(isExist);
Map map1 = new HashMap();
map1.put(123,"aa");
map1.put("aa",123);
map1.put("bb",456);
System.out.println(map.equals(map1));
}
@Test
public void test3(){
Map map = new HashMap();
map.put(123,1);
map.put(012,2);
map.put(456,4);
System.out.println(map);
}
@Test
// keySet:遍历key、value、key-value集合。
public void test4(){
Map map = new HashMap();
map.put(123,1);
map.put(012,2);
map.put(456,4);
// 遍历key
Set set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
// 遍历value
Collection values = map.values();
for (Object obj : values){
System.out.println(obj);
}
// 方式1:
Set keyValue = map.entrySet();
Iterator iterator1 = keyValue.iterator();
while (iterator1.hasNext()) {
// Object key = iterator1.next();
// Map.Entry entry = (Map.Entry)key;
// System.out.println(entry.getKey()+"===="+entry.getValue());
System.out.println(iterator1.next());
}
// 方式2:
Set keySet = map.keySet();
Iterator iterator2 = keySet.iterator();;
while(iterator2.hasNext()){
Object key = iterator2.next();
Object value = map.get(key);
System.out.println(key+"===="+value);
}
}
}



