java 自定义容器,实现foreach
import java.util.Arrays; import java.util.Iterator; public class ArrayList implements Iterable<Integer> { public int size; public int current = 0; Object[] objects = new Object[2]; public void add(Object o) { //当index超出最初定义数组的长度时,自动扩容 if(size == objects.length){ System.out.println("extend................"); System.out.println(size); objects = Arrays.copyOf(objects, objects.length + (objects.length << 1)); System.out.println(objects.length); } objects[size] = o; size++; } public int size(){ return size; } public int get(int i) {return (int)objects[i]; } public Iterator<Integer> iterator() { class iter implements Iterator<Integer> { @Override public boolean hasNext() { return (current < size); } @Override public Integer next() { return (int)objects[current++]; } @Override public void remove() { } } return new iter(); } public static void main(String[] args) { ArrayList a = new ArrayList(); a.add(23); a.add(67); a.add(98); a.add(989); a.add(9897); // for (int i = 0; i < a.size(); i++) // System.out.println(a.get(i)); for (Integer abc : a) { System.out.println(abc); } } }