Java HashMap HashSet HashTable与其遍历接口所使用的迭代器(iterator)

set和map区别

Set代表集合元素无序,集合元素不可重复的集合,Map代表一种由多个key-value组成的集合,map集合是set集合的扩展只是名称不同

HashMap和Hashtable都实现了Map接口,主要的区别:

Hashtable是synchronized 的支持多线程使用;
HashMap非synchronized的,可以接受null。

另一个区别:
HashMap的迭代器是fail-fast迭代器,而Hashtable的enumerator迭代器。HashMap可以通过
Map m = Collections.synchronizeMap(hashMap);进行同步:

两种 iterator 区别

快速失败(fail—fast)安全失败(fail—safe)
追求性能,直接迭代,集合内容变化时抛出异常(ConcurrentModificationException )复制一份再迭代,内容变化不影响被迭代集合,不会抛出异常
  • enumerator迭代器与Iterator 的区别

Enumeration 实例

 Hashtable hashtable = new Hashtable();
	hashtable.put("1", "11");
	hashtable.put("2", "22");
	Enumeration elements = hashtable.elements();//Hashtable 支持Enumeration 迭代器
	while(elements.hasMoreElements()){
		Object nextElement = elements.nextElement();
		System.out.println(nextElement);
		/*
		通过Enumeration,我们只能读取集合的数据,而不能对数据进行修改
		*/
	}

Iterator 实例

ArrayList arrayList = new ArrayList();
arrayList.add("11");
arrayList.add("22");

ListIterator<String> listIterator = arrayList.listIterator();
while (listIterator.hasNext()) {
	System.out.println(listIterator.next());
	listIterator.remove(); 
	
	/* listIterator的remove方法是Iterator迭代器特有的
	Iterator除了能读取集合的数据之外,也能数据进行删除操作*/
	
} 

HashMap和HashSet的区别

HashSet实现了Set接口,它不允许集合中有重复的值,HashMap实现了Map接口,Map接口对键值对进行映射。HashSet扩展了HashMap,所以底层还是用到map存储,存储实现同map一致,HashMap储存键值,HashSet存储对象。

总结

Map 包括HashMap和HashTable,多线程优先选择table,他们都是K/V的组成的集合,是映射;Set 用来存储对象。


版权声明:本文为gao511147456原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。