Map集合分类介绍(hashTable、treeMap、hashMap、linkedHashMap)

来源:互联网 发布:数据分析思路 编辑:程序博客网 时间:2024/05/29 19:02

首先Map与Collection在集合框架中属并列存在,相当于同级

Collection是单列集合, Map 是双列集合,Map存储的是键值对结构的数据(key-value)

Map存储元素使用put方法,Collection使用add方法

Map集合没有直接取出元素的方法,而是先转成Set集合,在通过迭代获取元素

Map集合中键要保证唯一性

Map集合分为:

1、HashTable:底层是哈希表数据结构,线程是同步的,不可以存入null键,null值。效率较低,被HashMap 替代。

2、TreeMap:底层是二叉树数据结构。可以对map集合中的键进行排序。需要使用Comparable或者Comparator 进行比较排序。return 0,来判断键的唯一性。

3、HashMap:底层是哈希表数据结构,线程是不同步的,可以存入null键,null值。要保证键的唯一性,需要覆盖hashCode方法,和equals方法。

3-1、LinkedHashMap:该子类基于哈希表又融入了链表。可以Map集合进行增删提高效率。

HashTable和HashMap的区别:http://blog.sina.com.cn/s/blog_599ed7120100dn2o.html

那么遍历Map集合的方式有3种:

1、将map 集合中所有的键取出存入set集合。Set<K>keySet()   返回所有的key对象的Set集合再通过get方法获取键对应的值。

import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set;public class Demo2 {public static void main(String[] args) {Map<Integer, String> map = new HashMap<Integer, String>();map.put(1, "aaaa");map.put(2, "bbbb");map.put(3, "cccc");System.out.println(map);// 需要分别获取key和value,没有面向对象的思想// Set<K> keySet() 返回所有的key对象的Set集合Set<Integer> ks = map.keySet();Iterator<Integer> it = ks.iterator();while (it.hasNext()) {Integer key = it.next();String value = map.get(key);System.out.println("key=" + key + " value=" + value);}}}
2、values() ,获取所有的值.Collection<V>values()不能获取到key对象

public static void main(String[] args) {Map<Integer, String> map = new HashMap<Integer, String>();map.put(1, "aaaa");map.put(2, "bbbb");map.put(3, "cccc");                System.out.println(map);// 通过values 获取所有值,不能获取到key对象// Collection<V> values()Collection<String> vs = map.values();Iterator<String> it = vs.iterator();while (it.hasNext()) {String value = it.next();System.out.println(" value=" + value);}}

3、Map.Entry对象 推荐使用;Set<Map.Entry<k,v>>entrySet(),将map 集合中的键值映射关系打包成一个对象,Map.Entry对象通过Map.Entry 对象的getKey,
getValue获取其键和值。

public static void main(String[] args) {Map<Integer, String> map = new HashMap<Integer, String>();map.put(1, "aaaa");map.put(2, "bbbb");map.put(3, "cccc");System.out.println(map);// Set<Map.Entry<K,V>> entrySet()// 返回的Map.Entry对象的Set集合 Map.Entry包含了key和value对象Set<Map.Entry<Integer, String>> es = map.entrySet();Iterator<Map.Entry<Integer, String>> it = es.iterator();while (it.hasNext()) {// 返回的是封装了key和value对象的Map.Entry对象Map.Entry<Integer, String> en = it.next();// 获取Map.Entry对象中封装的key和value对象Integer key = en.getKey();String value = en.getValue();System.out.println("key=" + key + " value=" + value);}}
TreeMap集合和TreeSet集合都是通过实现Comparable和Comparator这两个接口来比较判断值得唯一性;



阅读全文
0 0