Map接口的常用方法
一、添加、删除、修改
put(Object key, Object value)
Map map = new HashMap();
System.out.println("---put(Object key, Object value)---添加和修改");
//添加
map.put("AA", 123);
map.put(45, 123);
map.put("BB", 56);
System.out.println(map); //{AA=123, BB=56, 45=123}
//修改
map.put("AA", 87);
System.out.println(map); //{AA=87, BB=56, 45=123}
putAll(Map m)
System.out.println("---putAll(Map m)---");
//putAll()
Map map1 = new HashMap();
map1.put("CC", 123);
map1.put("DD", 123);
map.putAll(map1);
System.out.println(map); //{AA=87, BB=56, CC=123, DD=123, 45=123}
remove(Object key)
System.out.println("---remove(Object key)---");
//remove(Object key) 返回移除的key所对应的value值
Object value = map.remove("CC");
System.out.println(value); //123
System.out.println(map); //{AA=87, BB=56, DD=123, 45=123}
clear()
System.out.println("---clear()---");
map.clear();
System.out.println(map); //{}
System.out.println(map.size()); //0
二、元素查询
get(Object key)
Map map = new HashMap();
map.put("AA", 123);
map.put(45, 123);
map.put("BB", 56);
System.out.println("---get(Object key)---获取指定key的value");
Object value = map.get("BB");
System.out.println(value); //56
containsKey(Object key)
//containsKey()
System.out.println("---containsKey(Object key)---是否包含指定的key");
boolean isExist = map.containsKey("BB");
System.out.println(isExist); //true
containsValue(Object value)
//containsValue()
System.out.println("---containsValue(Object value)---是否包含指定的value");
isExist = map.containsValue(123);
System.out.println(isExist); //true
size()
//size()
System.out.println("---size()---返回map中key-value对的个数");
int size = map.size();
System.out.println(size); //3
isEmpty()
//isEmpty()
System.out.println("---isEmpty---判断当前map是否为空");
boolean isEmpty = map.isEmpty();
System.out.println(isEmpty); //false
equals(Object obj)
//equals(Obejct obj)
System.out.println("---equals()---判断当前map和参数对象obj是否相等");
Map map1 = new HashMap();
map1.put("AA", 123);
map1.put(45, 123);
map1.put("BB", 56);
boolean isequals = map.equals(map1);
System.out.println(isequals); //true
三、元视图操作的方法
keySet()
Map map = new HashMap();
map.put("AA", 123);
map.put(45, 123);
map.put("BB", 56);
//keySet()
System.out.println("---keySet()---返回所有key构成的Set集合");
Set set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
values()
//values()
System.out.println("---values()---返回所有value构成的Collection集合");
Collection values = map.values();
Iterator iterator1 = values.iterator();
while (iterator1.hasNext()){
System.out.println(iterator1.next());
}
entrySet()
//entrySet()
System.out.println("---entrySet()---返回所有key-value对构成的Set集合");
Set entrySet = map.entrySet();
Iterator iterator2 = entrySet.iterator();
while (iterator2.hasNext()){
System.out.println(iterator2.next());
}
总结:
添加:put()/putAll()
删除:remove()
修改:put()
查询:get()
长度:size()
遍历:keySet()/values()/entrySet()