自定义一个类使用增强for循环

package com.zyf.day19;

import java.util.Iterator;

//自定义一个类使用增强for循环
class MyList implements Iterable{
	Object[] arr = new Object[10];
	int index = 0;
	public void add(Object o){
		arr[index++] = o;
	}
	public int size(){
		return index;
	}
	@Override
	public Iterator iterator() {
		// TODO Auto-generated method stub
		return new Iterator(){
            int cursor = 0;
			@Override
			public boolean hasNext() {
				// TODO Auto-generated method stub
				return cursor < index;
			}

			@Override
			public String next() {
				// TODO Auto-generated method stub
				return (String) arr[cursor++];
			}

			@Override
			public void remove() {
				// TODO Auto-generated method stub
				
			}
			
		};
	}
}
public class demo2 {
    public static void main(String[] args) {
		MyList list = new MyList();
		list.add("张三");
		list.add("李四");
		list.add("王五");
		list.add("赵六");
		for(String item : list){
		System.out.println("list= " + item);
		}
	}
}

你可能感兴趣的:(java)