java - ArrayList 和 CircularArrayList 之间的主要区别是什么
问题描述
CircularArrayList
我想在不使用任何 Java API的情况下构建自己的。但是我上网冲浪并找不到 andArrayList
和 a之间的基本区别CircularArrayList
。我总是以循环队列的定义结束。
这两种数据结构的基本区别是什么?
解决方案
我没有直接回答这个问题,但是,我提供了如何使用 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
.
推荐阅读
- c# - 您可以仅对齐文本框中的部分文本吗?
- javascript - vanilla JS 日期对象可以在 React.js 中正常使用吗?
- checkbox - 如何让 Vuetify 复选框准确反映它的价值?
- android - 将 TextView 颜色设置为 Color.Argb(255, 255, 255, 255); 由于某种原因无法在 Xamarin.Android 上工作
- html - 删除 HTML 部分之间的空格
- list - Prolog - 制作清单
- java - 如果 DragEvent 正在运行,则不会触发 ScrollEvent
- c# - 如何从存储过程中检索类的值
- java - 按方法级别@Order注释对spring @Beans进行排序
- delphi - 我在使用 Application.ActivateHint 时缺少什么?