如何解决“只能迭代数组或java.lang.Iterable实例”

时间:2019-05-31 04:55:59

标签: java arraylist collections

我正在尝试在Java中实现自己的Arraylist类。但是当我遍历元素时,我得到了编译错误

我已经实现了可迭代的接口,并且还覆盖了迭代器方法:

public class ArrayList<E> implements List<E>, Serializable, Iterable<E> {

    // Constructor
    public ArrayList(int initialCapacity) {

        defaultCapacity = initialCapacity;
    }

    public ArrayList() {
    }

    @Override
    public boolean add(Object value) {
        ensureCapacity(currentCapacity);
        array[size] = value;
        size++;
        return false;
    }

    private void ensureCapacity(int currentCapacity) {

        if ((currentCapacity + 1) >= size) {
            growArray(currentCapacity);
        }
        return;
    }

    private void growArray(int currentCapacity) {

        if (currentCapacity >= maximumArraySize) {
            throw new IndexOutOfBoundsException("Array list size reached to its limit");
        }
        int initialcapacity = currentCapacity;

        currentCapacity = initialcapacity + (currentCapacity >> 1); // increase capacity by half
        Arrays.copyOf(array, currentCapacity);
    }

    @Override
    public E get(int index) {
        return (E) array[index];
    }

    @Override
    public void add(int index, E value) {

    }

    @Override
    public int getSize() {
        // TODO Auto-generated method stub
        return size;
    }

    @Override
    public Iterator<E> iterator() {
        return (Iterator<E>) Arrays.asList(array).iterator();
    }
}

但是当我尝试迭代时:

for (String a : list) {

        }

我收到编译错误:

Can only iterate over an array or an instance of java.lang.Iterable

0 个答案:

没有答案