基于HashMap遍历和使用方法(详解)
map的几种遍历方式:
map< string, string> map = new hashmap<>(); map.put("aa", "@sohu.com"); map.put("bb","@163.com"); map.put("cc", "@sina.com"); system.out.println("普通的遍历方法,通过map.keyset遍历key和value");//普通使用,二次取值 for (string key : map.keyset()) { system.out.println("key= "+key+" and value= "+map.get(key)); } system.out.println("通过map.entryset使用iterator遍历key和value:"); iterator<map.entry<string, string>> it = map.entryset().iterator(); while(it.hasnext()){ map.entry<string, string> entry = it.next(); system.out.println("key= "+entry.getkey()+" and value= "+entry.getvalue()); } system.out.println("通过map.entryset遍历key和value"); //推荐这种,特别是容量大的时候 for(map.entry<string, string> entry : map.entryset()){ system.out.println("key= "+entry.getkey()+" and value= "+entry.getvalue()); } system.out.println(“通过map.values()遍历所有的value,但不能遍历key”); for(string v : map.values()){ system.out.println("value = "+v); }
hashmap和hashtable的联系和区别
实现原理相同,功能相同,底层都是哈希表结构,查询速度快,在很多情况下可以互用,早期的版本一般都是安全的。
hashmap和hashtable都实现了map接口,但决定用哪一个之前先要弄清楚它们之间的分别。主要的区别有:线程安全性,同步(synchronization),以及速度。
hashmap几乎可以等价于hashtable,除了hashmap是非synchronized的,并可以接受null(hashmap可以接受为null的键值(key)和值(value),而hashtable则不行)。
hashmap是非synchronized,而hashtable是synchronized,这意味着hashtable是线程安全的,多个线程可以共享一个hashtable;而如果没有正确的同步的话,多个线程是不能共享hashmap的。java 5提供了concurrenthashmap,它是hashtable的替代,比hashtable的扩展性更好。
另一个区别是hashmap的迭代器(iterator)是fail-fast迭代器,而hashtable的enumerator迭代器不是fail-fast的。所以当有其它线程改变了hashmap的结构(增加或者移除元素),将会抛出concurrentmodificationexception,但迭代器本身的remove()方法移除元素则不会抛出concurrentmodificationexception异常。但这并不是一个一定发生的行为,要看jvm。这条同样也是enumeration和iterator的区别。
由于hashtable是线程安全的也是synchronized,所以在单线程环境下它比hashmap要慢。如果你不需要同步,只需要单一线程,那么使用hashmap性能要好过hashtable。
hashmap不能保证随着时间的推移map中的元素次序是不变的。
hashmap的特点
hashmap是map接口的子类,是将键映射到值的对象,其中键和值都是对象,不是线程安全的
hashmap用hash表来存储map的键
key是无序唯一,可以有一个为null
value无序不唯一,可以有对个null
linkedhashmap使用hash表存储map中的键,并且使用linked双向链表管理顺序
我们用的最多的是hashmap,在map 中插入、删除和定位元素,hashmap 是最好的选择。如果需要输出的顺序和输入的相同,那么用linkedhashmap 可以实现,它还可以按读取顺序来排列.
hashmap是一个最常用的map,它根据键的hashcode值存储数据,根据键可以直接获取它的值,具有很快的访问速度。hashmap最多只允许一条记录的键为null,允许多条记录的值为null。 hashmap不支持线程同步,即任一时刻可以有多个线程同时写hashmap,可能会导致数据的不一致性。
如果需要同步,可以用collections的synchronizedmap方法使hashmap具有同步的能力。linkedhashmap保存了记录的插入顺序,在用iterator遍历linkedhashmap时,先得到的记录肯定是先插入的。
hashmap可以通过下面的语句进行同步:
map m = collections.synchronizemap(hashmap);
几大常用集合的效率对比
以上这篇基于hashmap遍历和使用方法(详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。