首页 > 解决方案 > ArrayList 和 CircularArrayList 之间的主要区别是什么

问题描述

CircularArrayList我想在不使用任何 Java API的情况下构建自己的。但是我上网冲浪并找不到 andArrayList和 a之间的基本区别CircularArrayList。我总是以循环队列的定义结束。

这两种数据结构的基本区别是什么?

标签: javaarraylist

解决方案


我没有直接回答这个问题,但是,我提供了如何使用 Java 实现循环数组的代码,

class CircularArray<T> implements Iterable<T> {


    private T[] items;
    private int head = 0;

    public CircularArray(int size) {    
        items = (T[]) new Object[size];
    }

    private int convert(int index) {

        if (index < 0) {
            index += items.length;
        }

        return (head + index) % items.length;
    }

    public void rotate(int shiftRight) {

        head = convert(shiftRight);
    }

    public T get(int i) {

        if (i < 0 || i >= items.length) {

            throw new java.lang.IndexOutOfBoundsException("Index " + i + " is out of bounds");
        }

        return items[convert(i)];
    }

    public void set(int i, T item) {
        items[convert(i)] = item;
    }

    public Iterator<T> iterator() {
        return new CircularArrayIterator<T>(this);
    }


    private class CircularArrayIterator<TI> implements Iterator<TI> {


        private int current = -1;
        private TI[] items;

        public CircularArrayIterator(CircularArray<TI> circularArray) {
            items = circularArray.items;
        }

        @Override
        public boolean hasNext() {
            return current < items.length - 1;
        }

        @Override
        public TI next() {
            current++;
            TI item = (TI) items[convert(current)];
            return item;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("Remove is not supported by CircularArray");
        }
    }
}

现在,任务将是使用这个循环数组数据结构来创建一个自定义的循环ArrayList。但是,我不确定这在哪些情况下会有所帮助,因为我们无法扩展ArrayList类似的Array.


推荐阅读