Java Map接口常用方法

5 篇文章 0 订阅
3 篇文章 0 订阅

接口定义:

另个参数分别为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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值