【发布时间】:2017-09-21 02:47:38
【问题描述】:
我想知道 ArrayList 的 UnorderedList 的方法是什么样的。我知道我们会有 addToFront、addToRear 和 addAfter(都带有 T 元素),但我只见过用数组实现的(见下文)。是否可以使用 ArrayList 代替?这将如何改变方法?希望我的问题有意义。
这是我遇到的代码:
public void addToFront(T element) {
if (size() == list.length) {
expandCapacity();
}
for (int i = this.size(); i > 0; i--) {
this.list[i] = this.list[i-1];
}
this.list[0] = element;
this.rear++;
}
/**
* Adds the specified element to the rear of this list.
*
* @param element the element to be added to the list
*/
public void addToRear(T element) {
if (size() == list.length) {
expandCapacity();
}
this.list[rear] = element;
this.rear++;
}
/**
* Adds the specified element after the specified target element.
* Throws an ElementNotFoundException if the target is not found.
*
* @param element the element to be added after the target element
* @param target the target that the element is to be added after
*/
public void addAfter(T element, T target) {
if (size() == list.length) {
expandCapacity();
}
int scan = 0;
while (scan < rear && !target.equals(list[scan])) {
scan++;
}
if (scan == rear) {
throw new ElementNotFoundException("list");
}
scan++;
for (int scan2 = rear; scan2 > scan; scan2--) {
list[scan2] = list[scan2 - 1];
}
list[scan] = element;
rear++;
}
}
【问题讨论】:
-
不多。试一试。您的代码中使用的一些内置表示可能会更改。
-
@nullpointer 在扩展容量方面,ArrayList 是否需要这样做?我的知识可能有限,但它的容量不是自动增长的吗?
标签: java list arraylist unordered