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;
		}
    }
    
    @Override
	public Iterator<Entry> iterator() {
    	return entries.iterator();
	}

	public List<Entry> getEntries() {
		return entries;
	}
}

你可能感兴趣的:(java,foreach,Iterable,增强型For循环)