当前位置: 移动技术网 > IT编程>开发语言>Java > 详解JAVA中的for-each循环与迭代

详解JAVA中的for-each循环与迭代

2019年07月22日  | 移动技术网IT编程  | 我要评论

在学习java中的collection时注意到,collection层次的根接口collection实现了iterable<t>接口(位于java.lang包中),实现这个接口允许对象成为 "foreach" 语句的目标,而此接口中的唯一方法,实现的就是返回一个在一组 t 类型的元素上进行迭代的迭代器。

一、迭代器iterator

接口:iterator<t>

public interface iterator<e>{
  boolean hasnext(); 
 e next(); 
 void remove();
 }

查看iterator接口api可以知道,这是对collection进行迭代的迭代器。迭代器允许调用者利用定义良好的语义在迭代期间从迭代器所指向的 collection 移除元素。

尤其值得注意的是此迭代器remove()方法的使用:从迭代器指向的 collection 中移除迭代器返回的最后一个元素(可选操作)。每次调用 next 只能调用一次此方法。如果进行迭代时用调用此方法(remove方法)之外的其他方式修改了该迭代器所指向的 collection,则迭代器的行为是不确定的。 接口设计人员在设计iterator<t>接口的时候已经指出,在进行迭代时如果调用了除了迭代器的remove()方法修改了该迭代器所指向的collection,则会造成不确定的后果。具体出现什么后果依迭代器的具体实现而定。针对这种不确定的后果可能出现的情况,在学习arraylist时遇到了其中一种:迭代器抛出 concurrentmodificationexception异常。具体异常情况如下代码所示:

import java.util.arraylist;
import java.util.collection;
import java.util.iterator;

public class itaratortest {

  public static void main(string[] args) {
    collection<string> list = new arraylist<string>();
    list.add("android");
    list.add("ios");
    list.add("windows mobile");

    iterator<string> iterator = list.iterator();
    while (iterator.hasnext()) {
      string lang = iterator.next();
      list.remove(lang);//will throw concurrentmodificationexception
    }
  }

}

此段代码在运行时会抛出concurrentmodificationexception异常,因为我们在迭代器运行期间没有用iterator的remove()方法来删除元素,而是使用arraylist的 remove()方法改变了迭代器所指向的collection。这就违反了迭代器的设计原则,所以发生了异常。

所报异常情况如下所示:

exception in thread "main" java.util.concurrentmodificationexception
    at java.util.arraylist$itr.checkforcomodification(arraylist.java:859)
    at java.util.arraylist$itr.next(arraylist.java:831)
    at text.itaratortest.main(itaratortest.java:17)

二、for-each循环与迭代器iterator<t>

从java5起,在java中有了for-each循环,可以用来循环遍历collection和array。foreach循环允许你在无需保持传统for循环中的索引,或在使用iterator /listiterator(arraylist中的一种迭代器实现)时无需调用while循环中的hasnext()方法就能遍历collection。for-each循环简化了任何collection或array的遍历过程。但是使用foreach循环也有两点需要注意。

使用foreach循环的对象,必须实现了iterable<t>接口

请看如下示例:

import java.util.arraylist;

public class foreachtest1 {

  public static void main(string args[]) {
    customcollection<string> mycollection = new customcollection<string>();
    mycollection.add("java");
    mycollection.add("scala");
    mycollection.add("groovy");

    // what does this code will do, print language, throw exception or
    // compile time error
    for (string language : mycollection) {
      system.out.println(language);
    }
  }

  private class customcollection<t> {
    private arraylist<t> bucket;

    public customcollection() {
      bucket = new arraylist();
    }

    public int size() {
      return bucket.size();
    }

    public boolean isempty() {
      return bucket.isempty();
    }

    public boolean contains(t o) {
      return bucket.contains(o);
    }

    public boolean add(t e) {
      return bucket.add(e);
    }

    public boolean remove(t o) {
      return bucket.remove(o);
    }

  }
}

上述代码将无法通过编译,这是因为代码中的customcollection类没有实现iterable<t>接口,编译期的报错如下:

exception in thread "main" java.lang.error: unresolved compilation problem:
    can only iterate over an array or an instance of java.lang.iterable

    at text.foreachtest1.main(foreachtest1.java:15)

事实上,无需等到编译时才发现报错,eclipse会在这段代码写完之后就会在foreach循环处显示错误:can only iterate over an array or an instance of java.lang.iterable

从上述示例可以再次得到确认的是,foreach循环只适用于实现了iterable<t>接口的对象。由于所有内置collection类都实现了java.util.collection接口,已经继承了iterable,所以为了解决上述问题,可以选择简单地让customcollection实现collection接口或者继承abstractcollection。解决方式如下:

import java.util.abstractcollection;
import java.util.arraylist;
import java.util.iterator;

public class foreachtest {
  public static void main(string args[]) {
    customcollection<string> mycollection = new customcollection<string>();
    mycollection.add("java");
    mycollection.add("scala");
    mycollection.add("groovy");
    for (string language : mycollection) {
      system.out.println(language);
    }
  }

  private static class customcollection<t> extends abstractcollection<t> {
    private arraylist<t> bucket;

    public customcollection() {
      bucket = new arraylist();
    }

    public int size() {
      return bucket.size();
    }

    public boolean isempty() {
      return bucket.isempty();
    }

    public boolean contains(object o) {
      return bucket.contains(o);
    }

    public boolean add(t e) {
      return bucket.add(e);
    }

    public boolean remove(object o) {
      return bucket.remove(o);
    }

    @override
    public iterator<t> iterator() {
      // todo auto-generated method stub
      return bucket.iterator();
    }
  }
}

2.foreach循环的内部实现也是依靠iterator进行实现的

为了验证foreach循环是使用iterator作为内部实现这一事实,我们依然采用本文最开始的实例进行验证:

public class itaratortest {

  public static void main(string[] args) {
    collection<string> list = new arraylist<string>();
    list.add("android");
    list.add("ios");
    list.add("windows mobile");

    // example1
    // iterator<string> iterator = list.iterator();
    // while (iterator.hasnext()) {
    // string lang = iterator.next();
    // list.remove(lang);
    // }

    // example 2
    for (string language : list) {
      list.remove(language);
    }
  }

}

程序运行时所报异常:

exception in thread "main" java.util.concurrentmodificationexception
    at java.util.arraylist$itr.checkforcomodification(arraylist.java:859)
    at java.util.arraylist$itr.next(arraylist.java:831)
    at text.itaratortest.main(itaratortest.java:22)

此异常正说明了for-each循环内部使用了iterator来遍历collection,它也调用了iterator.next(),这会检查(元素的)变化并抛出concurrentmodificationexception。

总结:

  • 在遍历collection时,如果要在遍历期间修改collection,则必须通过iterator/listiterator来实现,否则可能会发生“不确定的后果”。
  • foreach循环通过iterator实现,使用foreach循环的对象必须实现iterable接口

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网