接口定义:
另个参数分别为K、V均为泛型表示。分别代表了Map中存入数值的key和Value的类型。
Map接口中定义的方法,为接口下类的通用方法,包括HashMap、HashTable等,均可直接使用对应的方法。
1、查看元素个数
int size();
2、判断Map是否为空
boolean isEmpty();
3、判断Map是否包括指定Key
boolean containsKey(Object key);
4、判断Map是否包括指定Value
boolean containsValue(Object value);
5、根据Key获取对应的Value
V get(Object key);
6、向Map中存入一组键值对
V put(K key, V value);
7、根据Key移出一组键值对
V remove(Object key);
8、将另一个Map中的数据复制到当前Map中
void putAll(Map<? extends K, ? extends V> m);
9、清空Map
void clear();
代码示例:
import java.util.*;
public class PutAndGet {
public static void main(String[] args) {
Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();
Map<Integer, Integer> map2 = new HashMap<Integer, Integer>();
map1.put(1, 100);
map1.put(2, 200);
map1.put(3, 300);
map2.put(11, 1100);
map2.put(12, 1200);
map2.put(13, 1300);
// 查看包含的元素个数
System.out.println(map1.size());
System.out.println(map1);
// 存入新的key为1的数据,覆盖原(1,100)
map1.put(1,99);
System.out.println(map1);
// 根据Key获取Value
System.out.println("map1 get key 2 is: "+map1.get(2));
// 判断是否包含某个Key或则Value
System.out.println("map1中有key为4的元素? "+map1.containsKey(4));
System.out.println("map1中有Value为300的元素? "+map1.containsValue(300));
// 将map2中的元素复制到map1中
map1.putAll(map2);
System.out.println("after copy, map1 now is: "+map1);
System.out.println("after copy, map2 now is: "+map2);
// 从map2中移出一组键值对(通过key)
map2.remove(12);
System.out.println("After remove 12, map2 is: "+map2);
// 清空map2
map2.clear();
System.out.println("After clear, map2 is: "+map2+" and size is: "+map2.size());
}
}
输出:
3
{1=100, 2=200, 3=300}
{1=99, 2=200, 3=300}
map1 get key 2 is: 200
map1中有key为4的元素? false
map1中有Value为300的元素? true
after copy, map1 now is: {1=99, 2=200, 3=300, 11=1100, 12=1200, 13=1300}
after copy, map2 now is: {11=1100, 12=1200, 13=1300}
After remove 12, map2 is: {11=1100, 13=1300}
After clear, map2 is: {} and size is: 0