给MyArrayList, 添加一个iterator方法用来遍历
package com.cskaoyan.www.day5;
import java.util.*;
public class MyArrayList <T> implements List<T> {
private static final int DEFAULT_CAPACITY = 10;
private static final int MAX_CAPACITY = Integer.MAX_VALUE - 8;
private Object[] elements;
private int size;
private int modCount;
public MyArrayList() {
elements = new Object[DEFAULT_CAPACITY];
}
public MyArrayList(int initialCapacity) {
if (initialCapacity <= 0 || initialCapacity > MAX_CAPACITY) {
throw new IllegalArgumentException("initialCapacity=" + initialCapacity);
}
elements = new Object[initialCapacity];
}
public Iterator<T> iterator(){
return new Itr();
}
class Itr implements Iterator<T> {
int cursor;
int expModCount = modCount;
int lastRet = -1;
@Override
public boolean hasNext() {
return cursor != size;
}
@Override
public T next() {
checkConModException();
if (!hasNext()) {
throw new NoSuchElementException();
}
lastRet = cursor;
cursor++;
return (T) elements[lastRet];
}
@Override
public void remove() {
checkConModException();
if (lastRet == -1) {
throw new IllegalStateException();
}
MyArrayList.this.remove(lastRet);
expModCount = modCount;
cursor = lastRet;
lastRet = -1;
}
private void checkConModException() {
if (expModCount != modCount) {
throw new ConcurrentModificationException();
}
}
}
@Override
public boolean add(T t) {
return false;
}
@Override
public boolean addAll(Collection<? extends T> c) {
return false;
}
@Override
public void add(int index, T element) {
}
@Override
public boolean addAll(int index, Collection<? extends T> c) {
return false;
}
@Override
public T remove(int index) {
return null;
}
@Override
public boolean remove(Object o) {
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
return false;
}
@Override
public boolean contains(Object o) {
return false;
}
@Override
public boolean containsAll(Collection<?> c) {
return false;
}
@Override
public T get(int index) {
return null;
}
@Override
public T set(int index, T element) {
return null;
}
@Override
public int indexOf(Object o) {
return 0;
}
@Override
public int lastIndexOf(Object o) {
return 0;
}
@Override
public boolean retainAll(Collection<?> c) {
return false;
}
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public void clear() {
}
@Override
public Object[] toArray() {
return new Object[0];
}
@Override
public <T1> T1[] toArray(T1[] a) {
return null;
}
@Override
public ListIterator<T> listIterator() {
return null;
}
@Override
public ListIterator<T> listIterator(int index) {
return null;
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
return null;
}
}