2 Star 0 Fork 0

CS-IMIS-23/zc20172324

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
UnorderedArray.java 2.37 KB
一键复制 编辑 原始数据 按行查看 历史
zc20172324 提交于 7年前 . pp6.8
package chap6;
import chap3.EmptyCollectionException;
import java.util.Arrays;
public class UnorderedArray<T> extends ArrayList<T> implements UnorderedListADT<T> {
public UnorderedArray() {
super();
}
public UnorderedArray(int initialCapacity) {
super(initialCapacity);
}
@Override
public void addToFront(T element) {
// 对数组进行扩容
if (size() == list.length) {
expandCapacity();
}
int scan = 0;
// 将现有元素向上移动1个
for (int shift = rear; shift > scan; shift--) {
list[shift] = list[shift - 1];
}
// 插入元素
list[scan] = element;
rear++;
modCount++;
}
@Override
public void addToRear(T element) {
if (size() == list.length) {
expandCapacity();
}
list[rear] = element;
rear++;
modCount++;
}
@Override
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("UnorderedList");
}
scan++;
// 将现有元素向上移动1个
for (int shift = rear; shift > scan; shift--) {
list[shift] = list[shift - 1];
}
// 插入元素
list[scan] = element;
rear++;
modCount++;
}
protected void expandCapacity() {
list = Arrays.copyOf(list, list.length * 2);
}
@Override
public T removeFirst() throws EmptyCollectionException
{
if (isEmpty()){
throw new EmptyCollectionException("ArrayList");
}
T result ;
result= list[0];
for (int i = 0; i < rear - 1;i++){
list[i] = list[i + 1];
}
list[rear - 1] = null;
rear--;
modCount++;
return result;
}
@Override
public T removeLast() throws EmptyCollectionException
{
if (isEmpty()){
throw new EmptyCollectionException("ArrayList");
}
T result ;
result= list[list.length-1];
list[rear] = null;
rear--;
modCount++;
return result;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/CS-IMIS-23/zc20172324.git
git@gitee.com:CS-IMIS-23/zc20172324.git
CS-IMIS-23
zc20172324
zc20172324
master

搜索帮助