Java语言基础Map集合

Map

Map
map用于保存具有映射关系的数据。
map有key和value两个值。
key是唯一的,不允许重复的值。
value是具体意义的数据。
key和value存在一对一对应的关系,即通过指定的key总能找到的指定的对应的value。

Hashmap
map在Java里是一个接口,而hashmap就是对map接口的具体实现,一般来讲,map集合指的就是hashmap类。
Hashtable
hashtable和hashtable是map接口的两个典型实现类。
hashtable是老的实现,线程安全,不允许使用 null 作为 key 或者 value。(hashmap与之相反)
两者都无顺序可言

Hashmap与Hastable判断两个key是否相等的标准:
hashmap和hashtable存key的值依据hashcode值(equals()方法返回true,说明两个key相同)。
hashtable相等的标准:两个Value通过 equalHashMap 判断两个 Values 方法返回True。

更新方法 查询方法
put() 添加数据 get() 根据key查找
remove() 根据Key值或者Key-Value对删除数据 size() map集合的长度
clear() 清空map集合 containsKey() 是否含有这个Key值
-------------- containsValue() 是否含有这个Value值

实现例:

//创建map集合
		Map<String, Integer> map = new HashMap<String, Integer>();
		
		//添加数据
		map.put("a", 1);
		map.put("b",1);
		map.put("c", 2);
		System.out.println(map);
		
//查询方法 
		  //get()
		System.out.println(map.get("b"));//根据key查找
		  //size()
		System.out.println(map.size());//map集合的长度
		  //containsKey()
		System.out.println(map.containsKey("a"));
		  //containsValue()
		System.out.println(map.containsValue(1));
//更新方法
		    //remove()
		map.remove("a");
		
		System.out.println(map);
		   //clear()
		map.clear();
		System.out.println(map);

输出:
{a=1, b=1, c=2}
1
3
true
true
{b=1, c=2}
{}

Map集合的遍历方法:

//遍历方法有两个
		map.keySet();//获取map集合的key
		map.values();//获取集合的value值
		//通过map.keySet()
		Set<String> keys = map.keySet();
		for(String key : keys) {
			System.out.println("key : "+key + ",value : " +map.get(key));
		}
		//通过map.entrySet()
		Set<Entry<String,Integer>> entrys = map.entrySet();
		//Entry是一个特殊对象,entrySet方法能将Map中的元素存入Set集合里
		for(Entry<String,Integer> en : entrys) {
			System.out.println("key : "+en.getKey()+", value : "+en.getValue());
		}

Treemap
Treemap存储Key-Value是有序的(根据Key)。
(1)自然排序:
key 实现 Compareble 接口,key 是同一个类。
一般排序按照字典顺序。
(2)定制排序:
创建 Treemap 时,传入 Comparetor 对象,这个对象负责对Treemap 中的 key 排序,不需要 Map 中的 Key 实现 Comparetanle 接口。

实现例:

Map<Integer,String> map1 = new TreeMap<Integer,String>();
		map1.put(4,"a");
		map1.put(2,"b");
		map1.put(3,"c");
		map1.put(1,"d");
		System.out.println(map1);
		
		Map<String,String> map2 = new TreeMap<String, String>();
		map2.put("b","123");
		map2.put("c","456");
		map2.put("a","789");
		map2.put("d","101");
		System.out.println(map2);

输出:
{1=d, 2=b, 3=c, 4=a}
{a=789, b=123, c=456, d=101}

发布了10 篇原创文章 · 获赞 3 · 访问量 821

猜你喜欢

转载自blog.csdn.net/sdutxkszy/article/details/105585493