ArrayList、LinkedList、HashMap是Java中常用到的几种集合类型,遍历它们是时常遇到的情况。当然还有一些变态的时候,那就是在遍历的过程中动态增加或者删除其中的元素。

下面的例子就是可以实现动态遍历ArrayList、LinkedList、HashMap。

 import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry; /**
* @Description:
* @author Scott
* @date 2014年2月21日 下午8:33:40
*/
public class TraversalTest { ArrayList<String> arrayList = new ArrayList<String>();
LinkedList<String> linkedList = new LinkedList<String>();
HashMap<String, String> map = new HashMap<String, String>(); public TraversalTest() {
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5"); linkedList.add("1");
linkedList.add("2");
linkedList.add("3");
linkedList.add("4");
linkedList.add("5"); map.put("1", "1");
map.put("2", "2");
map.put("3", "3");
map.put("4", "4");
map.put("5", "5"); System.out.println("Data has init over ...");
} /**
* ForEach Traversal.
* The Effective-Java recommended this traversal type.
* */
public void arrayListTraversalNormal1() {
System.out.println("ArrayList ForEach Traversal.");
for(String str : arrayList){
System.out.println(str);
}
} /**
* Iterator Traversal.
* */
public void arrayListTraversalNormal2() {
System.out.println("ArrayList Iterator Traversal.");
Iterator<String> itor = arrayList.iterator();
while(itor.hasNext()){
System.out.println(itor.next().toString());
}
} /**
* ForEach Traversal.
* The Effective-Java recommended this traversal type.
* */
public void linkedListTraversalNormal1() {
System.out.println("LinkedList ForEach Traversal.");
for(String str : linkedList){
System.out.println(str);
}
} /**
* Iterator Traversal.
* */
public void linkedListTraversalNormal2() {
System.out.println("LinkedList Iterator Traversal.");
Iterator<String> itor = linkedList.iterator();
while(itor.hasNext()){
System.out.println(itor.next().toString());
}
} public void mapTraversalNormal() {
System.out.println("HashMap Iterator Traversal.");
Iterator<Entry<String, String>> itor = map.entrySet().iterator();
Entry<String, String> entry = null;
String key = null;
String value = null; while(itor.hasNext()){
entry = itor.next();
key = entry.getKey();
value = entry.getValue(); System.out.println("key is " + key + ", value is " + value);
}
} /**
* While traversing the arrayList, add '33' behind the '3' element.
* */
public void arrayListTraversalDynamic1() {
ListIterator<String> itor = arrayList.listIterator();
String str = null; while (itor.hasNext()) {
str = itor.next().toString();
if(str.equals("3")){
itor.add("33");
break;
}
}
} /**
* While traversing the arrayList, remove the '3' element.
* */
public void arrayListTraversalDynamic2() {
ListIterator<String> itor = arrayList.listIterator();
String str = null; while (itor.hasNext()) {
str = itor.next().toString();
if(str.equals("3")){
itor.remove();
break;
}
}
} /**
* While traversing the linkedList, add '33' behind the '3' element.
* */
public void linkedListTraversalDynamic1() {
ListIterator<String> itor = linkedList.listIterator();
String str = null; while (itor.hasNext()) {
str = itor.next().toString();
if(str.equals("3")){
itor.add("33");
break;
}
}
} /**
* While traversing the linkedList, remove the '3' element.
* */
public void linkedListTraversalDynamic2() {
ListIterator<String> itor = linkedList.listIterator();
String str = null; while (itor.hasNext()) {
str = itor.next().toString();
if(str.equals("3")){
itor.remove();
break;
}
}
} /**
* While traversing the arrayList, add '33' when we get the '3' element.
* */
@SuppressWarnings("rawtypes")
public void mapTraversalDynamic1() {
LinkedList<Map.Entry<String, String>> tempList = new LinkedList<Map.Entry<String, String>>();
tempList.addAll(map.entrySet());
ListIterator<Map.Entry<String, String>> itor = tempList.listIterator();
Map.Entry entry = null; while (itor.hasNext()) {
entry = (Map.Entry) itor.next();
Object key = entry.getKey(); if (key.toString().equals("3")) {
map.put("33", "33");
}
}
} /**
* While traversing the hashMap, remove the '3' element.
* */
@SuppressWarnings("rawtypes")
public void mapTraversalDynamic2() {
LinkedList<Map.Entry<String, String>> tempList = new LinkedList<Map.Entry<String, String>>();
tempList.addAll(map.entrySet());
ListIterator<Map.Entry<String, String>> itor = tempList.listIterator();
Map.Entry entry = null; while (itor.hasNext()) {
entry = (Map.Entry) itor.next();
Object key = entry.getKey(); if(key.toString().equals("3")){
map.remove("3");
break;
}
}
} public static void main(String[] args) {
TraversalTest test = new TraversalTest(); test.arrayListTraversalNormal1();
test.arrayListTraversalNormal2(); System.out.println("While traversing the arrayList, add '33' behind the '3' element. The result is:");
test.arrayListTraversalDynamic1();
test.arrayListTraversalNormal1(); System.out.println("While traversing the arrayList, remove the '3' element. The result is:");
test.arrayListTraversalDynamic2();
test.arrayListTraversalNormal1(); System.out.println("-----------------------------------"); test.linkedListTraversalNormal1();
test.linkedListTraversalNormal2(); System.out.println("While traversing the linkedList, add '33' behind the '3' element. The result is:");
test.linkedListTraversalDynamic1();
test.linkedListTraversalNormal1(); System.out.println("While traversing the linkedList, remove the '3' element. The result is:");
test.linkedListTraversalDynamic2();
test.linkedListTraversalNormal1(); System.out.println("-----------------------------------");
test.mapTraversalNormal(); System.out.println("While traversing the hashMap, add '33' when we get the '3' element. The result is:");
test.mapTraversalDynamic1();
test.mapTraversalNormal(); System.out.println("While traversing the hashMap, remove the '3' element. The result is:");
test.mapTraversalDynamic2();
test.mapTraversalNormal();
} }

代码是最好的说明,运行结果如下:

Data has init over ...
ArrayList ForEach Traversal.
1
2
3
4
5
ArrayList Iterator Traversal.
1
2
3
4
5
While traversing the arrayList, add '33' behind the '3' element. The result is:
ArrayList ForEach Traversal.
1
2
3
33
4
5
While traversing the arrayList, remove the '3' element. The result is:
ArrayList ForEach Traversal.
1
2
33
4
5
-----------------------------------
LinkedList ForEach Traversal.
1
2
3
4
5
LinkedList Iterator Traversal.
1
2
3
4
5
While traversing the linkedList, add '33' behind the '3' element. The result is:
LinkedList ForEach Traversal.
1
2
3
33
4
5
While traversing the linkedList, remove the '3' element. The result is:
LinkedList ForEach Traversal.
1
2
33
4
5
-----------------------------------
HashMap Iterator Traversal.
key is 3, value is 3
key is 2, value is 2
key is 1, value is 1
key is 5, value is 5
key is 4, value is 4
While traversing the hashMap, add '33' when we get the '3' element. The result is:
HashMap Iterator Traversal.
key is 3, value is 3
key is 2, value is 2
key is 1, value is 1
key is 5, value is 5
key is 4, value is 4
key is 33, value is 33
While traversing the hashMap, remove the '3' element. The result is:
HashMap Iterator Traversal.
key is 2, value is 2
key is 1, value is 1
key is 5, value is 5
key is 4, value is 4
key is 33, value is 33

-------------------------------------------------------------------------------

如果您看了本篇博客,觉得对您有所收获,请点击右下角的 [推荐]

如果您想转载本博客,请注明出处

如果您对本文有意见或者建议,欢迎留言

感谢您的阅读,请关注我的后续博客

ArrayList、LinkedList、HashMap的遍历及遍历过程中增、删元素的更多相关文章

  1. arrayList LinkedList HashMap HashTable的区别

    ArrayList 采用的是数组形式来保存对象的,这种方式将对象放在连续的位置中,所以最大的缺点就是插入删除时非常麻烦 LinkedList 采用的将对象存放在独立的空间中,而且在每个空间中还保存下一 ...

  2. JDK1.7源码阅读tools包之------ArrayList,LinkedList,HashMap,TreeMap

    1.HashMap 特点:基于哈希表的 Map 接口的实现.此实现提供所有可选的映射操作,并允许使用 null 值和 null 键.(除了非同步和允许使用 null 之外,HashMap 类与 Has ...

  3. Java Map在遍历过程中删除元素

    Java中的Map如果在遍历过程中要删除元素,除非通过迭代器自己的remove()方法,否则就会导致抛出ConcurrentModificationException异常.JDK文档中是这么描述的: ...

  4. 设计模式系列之迭代器模式(Iterator Pattern)——遍历聚合对象中的元素

    模式概述 模式定义 模式结构图 模式伪代码 模式改进 模式应用 模式在JDK中的应用 模式在开源项目中的应用 模式总结 说明:设计模式系列文章是读刘伟所著<设计模式的艺术之道(软件开发人员内功修 ...

  5. 有关《查找两个List中的不同元素》的问题解答与编程实践

     郑海波 2013-07-08 问题: 有List<String> list1和List<String> list2,两个集合各有上万个元素,怎样查找两个集合中不同的元素呢? ...

  6. Hashtable,HashMap,TreeMap有什么区别?Vector,ArrayList,LinkedList有什么区别?int和Integer有什么区别?

    接着上篇继续更新. /*请尊重作者劳动成果,转载请标明原文链接:*/ /*https://www.cnblogs.com/jpcflyer/p/10759447.html* / 题目一:Hashtab ...

  7. Java泛型底层源码解析-ArrayList,LinkedList,HashSet和HashMap

    声明:以下源代码使用的都是基于JDK1.8_112版本 1. ArrayList源码解析 <1. 集合中存放的依然是对象的引用而不是对象本身,且无法放置原生数据类型,我们需要使用原生数据类型的包 ...

  8. 【java基础】java中ArrayList,LinkedList

    [一]ArrayList 一ArrayList的内部结构 (1)ArrayList内部维护的是一个Object数组 (2)ArrayList数组扩容后数组的长度的公式:旧的数组长度+(旧数组长度> ...

  9. LinkedList,ArrayList,Vector,HashMap,HashSet,HashTable之间的区别与联系

    在编写java程序中,我们最常用的除了八种基本数据类型,String对象外还有一个集合类,在我们的的程序中到处充斥着集合类的身影!java中集合大家族的成员实在是太丰富了,有常用的ArrayList. ...

随机推荐

  1. 利用PhantomJS搭建Highcharts export服务

    利用PhantomJS搭建Highcharts export服务 一直在使用Highcharts做web图表的展示, 但是当发送定时的报表邮件的遇到了这个问题. 为了保证邮件图表和web页图表样式一致 ...

  2. Xwindow的文章

    http://blog.csdn.net/crond123/article/details/5733776 http://bbs.csdn.net/topics/90377015 http://bbs ...

  3. ios ableviewcell的动态加载数据,模仿喜马拉雅动态数据加载

    iphone(UITableViewCell)动态加载图片http://developer.apple.com/library/ios/#samplecode/LazyTableImages/Intr ...

  4. HBase学习笔记

    关键类: HBaseAdmin 管理Hbase的,主要负责DDL操作 HTable 管理表中数据,主要负责DML操作 1.为了避免热点,更多的建表方法 在Shell中: },{SPLITS=>[ ...

  5. Android开发之网络请求HttpURLConnection

    转:http://blog.csdn.net/guolin_blog/article/details/12452307 Android中主要提供了两种方式来进行HTTP操作,HttpURLConnec ...

  6. openfire的配置

    Openfire 采用Java开发,开源的实时协作(RTC)服务器基于XMPP(Jabber)协议.Openfire安装和使用都非常简单,并利用Web进行管理.单台服务器可支持上万并发用户.所以常常被 ...

  7. Oracle默认的用户名和密码

    你是说默认的用户名和密码么scott 密码是 tigersys 密码是 change_on_installsystem 密码是 managersysman 密码是 oem_temp 其中直接管理模式可 ...

  8. Linux中 干掉原来的PHP方法

    干掉原来的PHP方法: 查看php版本命令:#php -v这个命令是删除不干净的#yum remove php因为使用这个命令以后再用#php -v还是会看到有版本信息的..... 必须强制删除#rp ...

  9. Linux编译安装Darwin Streaming Server 6.0.3

    买回来VPS后就一直想在上面搭建一个流媒体服务,在网上搜索了很多资料,大部分都是介绍Linux中安装Darwin Streaming Server 5.5.5版本,因为这个版本提供了针对linux的安 ...

  10. 在Android应用中使用Clean架构

    自从开始开发安卓应用,我一直感觉我可以做得更好.我看过不少烂代码,其中当然有我写的.安卓系统的复杂性加上烂代码势必酿成灾祸,所以从错误中成长就很重要.我Google了如何更好地开发应用,发现了这个叫做 ...