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. Resource is out of sync with the file system的解决办法

    在eclipse中,启动server时报此错,是因为文件系统不同步造成的,解决方法有两个: (1)选中工程,右键,选择F5(手动刷新): (2)Window->Preferences->G ...

  2. 告别无止境的增删改查:Java代码生成器

    对于一个比较大的业务系统,我们总是无止境的增加,删除,修改,粘贴,复制,想想总让人产生一种抗拒的心里.那有什么办法可以在正常的开发进度下自动生成一些类,配置文件,或者接口呢?   有感于马上要做个比较 ...

  3. 车牌识别LPR(一)-- 研究背景

    在年尾用了几天的时间将2014年的所有工作都总结了一遍,将之前的文档综合了下. 以下是LPR系统,车牌识别的一些总结资料. 第一篇:LPR研究背景 汽车的出现改变了以往出行徒步和以马代步的时代,极大地 ...

  4. Android log日志

    LOG是用来记录程序执行过程的机制,它既可以用于程序调试,也可以用于产品运营中的事件记录.在Android系统中,提供了简单.便利的LOG机制,开发人员可以方便地使用. androidsdk中提供了l ...

  5. 1008. Image Encoding(bfs)

    1008 没营养的破题 #include <iostream> #include<cstdio> #include<cstring> #include<alg ...

  6. android线程池

    线程池的基本思想还是一种对象池的思想,开辟一块内存空间,里面存放了众多(未死亡)的线程,池中线程执行调度由池管理器来处理.当有线程任务时,从池中取一个,执行完成后线程对象归池,这样可以避免反复创建线程 ...

  7. usaco /the first wave

    bzoj1572:贪心.先按时间顺序排序,然后用优先队列,如果时间不矛盾直接插入,否则判断队列中w最小的元素是否替换掉.(没用llWA了一次 #include<cstdio> #inclu ...

  8. IIS Web负载均衡的几种方式

    Web负载均衡的几种实现方式 摘要:负载均衡(Load Balance)是集群技术(Cluster)的一种应用.负载均衡可以将工作任务分摊到多个处理单元,从而提高并发处理能力.目前最常见的负载均衡应用 ...

  9. 在win7系统下使用TortoiseGit(乌龟git)简单操作Git@OSC

    非常感谢OSC提供了这么好的一个国内的免费的git托管平台.这里简单说下TortoiseGit操作的流程.很傻瓜了 首先你要准备两个软件,分别是msysgit和tortoisegit,乌龟还可以在下载 ...

  10. Java 单元测试(Junit)

    在有些时候,我们需要对我们自己编写的代码进行单元测试(好处是,减少后期维护的精力和费用),这是一些最基本的模块测试.当然,在进行单元测试的同时也必然得清楚我们测试的代码的内部逻辑实现,这样在测试的时候 ...