标签:修改 判断 返回 public entryset == 相等 keyset 添加
Object put(Object key,Object value):将指定key-value添加到(或修改)当前map对象中
void putAll(Map m):将m中的所有key-value对存放到当前map中
Object remove(Object key):移除指定key的key-value对,并返回value
void clear():清空当前map中的所有数据
@Test
public void test3(){
Map map = new HashMap();
map.put("AA",123);//添加
map.put(45,123);
map.put("BB",56);
map.put("AA",87);//修改
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.clear();//与map = null操作不同
System.out.println(map.size());
System.out.println(map);
}
Object get(Object key):获取指定key对应的value
boolean containsKey(Object key):是否包含指定的key
boolean containsValue(Object value):是否包含指定的value
int size():返回map中key-value对的个数
boolean isEmpty():判断当前map是否为空
boolean equals(Object obj):判断当前map和参数对象obj是否相等
@Test
public void test4(){
Map map = new HashMap();
map.put("AA",123);
map.put(45,123);
map.put("BB",56);
//Object get(Object key)
System.out.println(map.get(45));
//boolean containsKey(Object key)
boolean isExist = map.containsKey("BB");
System.out.println(isExist);
isExist = map.containsValue(123);
System.out.println(isExist);
map.clear();
System.out.println(map.isEmpty());
}
Set keySet():返回所有key构成的Set集合
Collection values():返回所有value构成的Collection集合
Set entrySet():返回所有key-value对构成的Set集合
@Test
public void test5(){
Map map = new HashMap();
map.put("AA",123);
map.put(45,123);
map.put("BB",56);
//遍历所有的key集:keySet()
Set set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println("=======================");
//遍历所有的value集:values()
Collection values = map.values();
for(Object obj : values){
System.out.println(obj);
}
System.out.println("=======================");
//遍历所有的key-value
//方式一:entrySet():
Set entrySet = map.entrySet();
Iterator iterator1 = entrySet.iterator();
while (iterator1.hasNext()){
Object o = iterator1.next();
//entrySet集合中的元素都是entry
Map.Entry entry = (Map.Entry) o;
System.out.println(entry.getKey() + "----->" + entry.getValue());
}
System.out.println("=======================");
//方式二:
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);
}
}
标签:修改 判断 返回 public entryset == 相等 keyset 添加
原文地址:https://www.cnblogs.com/koito/p/14924798.html