您的位置:首页 > 其它

Map以及Set的遍历(EntrySet方法,补充enumeration和Iterator的区别)

2015-11-15 16:34 459 查看
public void mearge(Map map) {
Map returnMap = new HashMap<>();
// 转换为Entry
Set<Map.Entry<Object, Object>> entries = map.entrySet();
// 遍历
for (Map.Entry<Object, Object> entry : entries) {
Object key = entry.getKey();
Object val = entry.getValue();
System.out.println("key:value#"+key+":"+val);
}
}


主要使用了Map.entrySet()方法;Entry可以理解为单个的键值对。

这里也跳过了set转为iterator再进行遍历的过程。直接使用foreach的方式,简洁。

补充一个关于Enumeration和iterator的知识点,之前看到有博文指出,尽量少用enumeration,多用iterator。

Enumeration接口主要实现的两个方法:

boolean
hasMoreElements()

Tests if this enumeration contains more elements.
E
nextElement()

Returns the next element of this enumeration if this enumeration object has at least one more element to provide.
  ·boolean hasMoreElemerts() :测试Enumeration枚举对象中是否还含有元素,如果返回true,则表示还含有至少一个的元素。
·Object nextElement() :如果Bnumeration枚举对象还含有元素,该方法得到对象中的下一个元素。

Iterator接口主要方法:

boolean
hasNext()

Returns
true
if the iteration has more elements.

E
next()

Returns the next element in the iteration.

void
remove()

Removes from the underlying collection the last element returned by this iterator (optional operation).

以上可以看出,iterator比enumeration多了个删除的方法,其他两个方法功能都相似,所以建议多使用iterator接口。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: