java基础-迭代器(Iterator)与增强for循环

时间:2023-03-08 15:33:56

              java基础-迭代器(Iterator)与增强for循环

                                    作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

一.Iterator迭代器概述

  Java中提供了很多个集合,它们在存储元素时,采用的存储方式不同。我们需要取出这些集合中的元素,可通过一种通用的方式来完成。

  Collection集合元素的通用获取方式:在取元素之前先要判断集合中有没有元素,如果有,就把这个元素取出来,继续在判断,如果还有就在取出来。一直把集合中所有的元素全部取出。这种取出方式专业术语称为迭代。换句话说,迭代是取出集合中元素的一种方式,因为Collection中有iterator方法,所以每一个子类集合对象都是迭代器对象。

二.迭代器的实现原理

  其实集合中的迭代器就是获取结合中元素的方式。这是时候我们就不得不说一下Iterator接口了,经过查阅API文档发现它有三个抽象方法,如下:

java基础-迭代器(Iterator)与增强for循环

  由于Iterator只是接口,不能被直接实例化,因此想要使用该接口就必须实现该接口的所有抽象方法,而我们学习的Collection接口也定影实现Iterator接口的抽象方法,即“iterator()”。因此只要是Collection的实现类就必须重写“iterator()”方法,最终返回“Iterator”接口实现类的对象(也就是可迭代对象),然后在调用hasNext()和next()方法来对集合进行迭代操作。

  综上所述,我们可以总结为以下三点:

    1>.迭代器不保证取出来元素的顺序和存入的顺序一致,“有序”是靠集合实例本身保证的;

    2>.迭代器本身是一个接口,该方法返回的是一个迭代器实例对象,通常使用的是接口多态使用迭代器;

    3>.迭代器中常用的两个方法是:

                  a>.boolean    hasNext() :  用来判断结合中是否有下一个元素可以迭代,如果返回true,说明可以迭代。

                  b>.Object      next()  :   用来返回迭代的下一个元素,并把指针向后移动一位。

  迭代器的执行过程,可以用张图来帮助大家理解,如下:

java基础-迭代器(Iterator)与增强for循环

三.迭代器的代码实现

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note; import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator; public class IteratorDemo {
public static void main(String[] args) {
Collection<String> coll = new ArrayList<String>();
coll.add("yinzhengjie");
coll.add("尹正杰");
coll.add("java");
coll.add("python");
coll.add("shell");
coll.add("golang"); //调用集合的方法iterator()获取出,Iterator接口的实现类的对象
Iterator<String> it1 = coll.iterator(); System.out.println("第一种方式进行迭代:");
//1>.用while循环遍历集合进行迭代
while(it1.hasNext()) {
System.out.println("\t"+it1.next());
} System.out.println("第二种方式进行迭代:");
//2>.用for循环进行迭代(相对while循环更节省内存,因为it2是for局部遍历,而it1是main方法的变量)
for(Iterator<String> it2 = coll.iterator();it2.hasNext();) {
System.out.println("\t"+it2.next());
} System.out.println("第三种方式进行迭代:");
//3>.用foreach循环(也叫增强for循环)继续迭代,需要JDK1.5版本以后才可以哟!
for (String string : coll) {
System.out.println("\t"+string);
}
}
} /*
以上代码执行结果如下:
第一种方式进行迭代:
yinzhengjie
尹正杰
java
python
shell
golang
第二种方式进行迭代:
yinzhengjie
尹正杰
java
python
shell
golang
第三种方式进行迭代:
yinzhengjie
尹正杰
java
python
shell
golang
*/

四.集合迭代过程中的转型

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note; import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator; public class IteratorDemo {
public static void main(String[] args) {
Collection<String> coll = new ArrayList<String>();
coll.add("yinzhengjie");
coll.add("尹正杰");
coll.add("Java"); Iterator it = coll.iterator();
while(it.hasNext()){
Object obj = it.next();
if(obj instanceof String) {
String str = (String)obj;
System.out.println(str.length());
}
}
}
} /*
以上代码执行结果如下:
11
3
4
*/

五.增强for循环遍历数组

  增强for循环是JDK1.5以后出来的一个高级for循环,专门用来遍历数组和集合的,它的内部原理其实是一个Iterator迭代器,所以在遍历的过程中,不能对集合中的元素进行增删操作。JDK1.5版本后,出现新的接口,即“java.lang.Iterable”。只要实现“java.lang.Iterable”这个接口,就允许对象称为增强for循环(“foreach”语句,注意“foreach”并不是关键字哟!)的目标。

 格式如下:
for( 数据类型 变量名:数组或这集合){
System.out.println(变量名);
}

  如果只做遍历的话,推荐大家使用增强for循环, 因为for循环存在优点的同时也会存在缺点。

    优点:代码少了,方便对容器遍历。

    缺点:没有索引,不能操作容器里面的元素。

  接下来我们用foreach来遍历数组和集合,代码如下:

1>.遍历数组

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note; public class ForeachDemo {
public static void main(String[] args) { String[] arr = {"yinzhengjie","org","cn"};
for (String string : arr) {
System.out.println(string+"\t\t"+string.length());
}
}
} /*
以上代码执行结果如下:
yinzhengjie 11
org 3
cn 2
*/

2>.遍历集合

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note; import java.util.ArrayList;
import java.util.Collection; class Student{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
}
//这里我们重写一下toString方法!方便System.out.pirntln在调用该对象的toString方法时不会去找Object的默认返回值。
public String toString() {
return this.name + "---" + this.age; }
} public class ForeachDemo {
public static void main(String[] args) {
//接口多态
Collection<Student> coll = new ArrayList<>();
coll.add(new Student("yinzhengjie",18));
coll.add(new Student("尹正杰",20)); for (Student p : coll) {
System.out.println(p);
}
}
} /*
以上代码执行结果如下:
yinzhengjie 11
org 3
cn 2
*/