JAVA基础(002_forEach的实现原理)

forEach的实现原理

核心:forEach遍历的实现是对迭代器的使用。在API中,对Iterable<T>接口有这样的描述,实现此接口,允许对象成为”for-each loop”语法的target。

public interface Iterable<T>

Implementing this interface allows an object to be the target of the “for-each loop” statement.

以List集合为例:List<E>接口继承了Collection<E>接口,而Collection<E>接口继承了Iterable<E>接口。Iterable<E>接口中定义了迭代器。

  • public interface Collection<E> extends Iterable<E>
  • public interface List<E> extends Collection<E>
API源码如下(JDK8):

public interface Iterable<T> {

    Iterator<T> iterator();

    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

    default Spliterator<T> spliterator() {
    return Spliterators.spliteratorUnknownSize(iterator(), 0);
    }
}

forEach遍历示例:

public class MainClass {

    public class User {

        private String username;
        private String password;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

    }

    public static void main(String[] args) {
        // 添加测试数据
        List<User> users = new ArrayList<User>();
        for (int i = 0; i < 5; i++) {
            User user = new MainClass().new User();
            user.setUsername("张三" + i);
            user.setPassword("00000" + i);
            users.add(user);
        }
        // forEach遍历
        for (User user : users) {
            System.out.println("username: " + user.getUsername() + "," + " " + "password: " + user.getPassword());
        }
    }
}

官方文档:
http://docs.oracle.com/javase/8/docs/api/index.html
http://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html

阅读更多
文章标签: java
个人分类: Java
上一篇JAVA基础(001_Collection与Collections的区别)
下一篇JAVA基础(003_Iterator浅析)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭