首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java For-each Loop & Iterable | 增强型For循环跟Iterable接口

2012-12-18 
Java For-each Loop & Iterable|增强型For循环和Iterable接口增强型For循环没什么好说的,Just see links:h

Java For-each Loop & Iterable | 增强型For循环和Iterable接口
 
增强型For循环没什么好说的,Just see links:
http://www.leepoint.net/notes-java/flow/loops/foreach.html
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

本篇唯一想说的是,如何在自定义的数据结构或说对象容器上使用增强型For循环?答案是让自定义的数据结构实现Iterable<T>接口。

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<MyList.Entry> {private List<Entry> entries = new ArrayList<Entry>();    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;}    }        @Overridepublic Iterator<Entry> iterator() {    return entries.iterator();}public List<Entry> getEntries() {return entries;}}

热点排行