---
title: "Java For-each Loop & Iterable  |  增强型For循环和Iterable接口"
author: "Wuaner"
date: "2012-09-11T21:50:19Z"
tags: ["Java", "foreach", "iterable", "增强型For循环"]
categories: ["编程语言"]
slug: "java-for-each-loop-iterable-for-iterable"
draft: false
lastmod: "2012-09-11T22:55:46Z"
id: 1676202
url: "https://wuaner.iteye.com/blog/1676202"
---

增强型For循环没什么好说的，Just see links： \[url]http://www.leepoint.net/notes-java/flow/loops/foreach.html\[/url] \[url]http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html\[/url] 本篇唯一想说的是，如何在自定义的数据结构或说对象容器上使用增强型For循环？答案是让自定义的数据结构实现Iterable接口。\[code="java"]import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class IterableTest { public static void main(String\[] args) { MyList myList = new MyList(); myList.getEntries().add(new MyList.Entry(1,"zhang")); myList.getEntries().add(new MyList.Entry(2,"liu")); for (MyList.Entry entry : myList) { System.out.println(entry.getId() + " : " + entry.getName()); } } } class MyList implements Iterable { private List entries = new ArrayList(); public static class Entry { private int id; private String name; public Entry(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } } @Override public Iterator iterator() { return entries.iterator(); } public List getEntries() { return entries; } }\[/code]