利用数组实现Java ArrayList类的基本功能,要求实现方法包括: Add, Insert, Delete, Find 编写一个测试应

2024-07-11 22:58:55
推荐回答(1个)
回答(1):

提供给你思路,这里我只做往数组里加int数字,其实可以做泛型的,如果你想深研究自己去看JDK源码。 我这里只是简单的做数组之间的复制。代码略长:不懂追问!

public class MyList {
private int size;
Object[] object = null;
Object[] temp;
int sequence = 0;

public MyList() {
this(1);
}

public MyList(int size) {
if (size <= 0) {
throw new IllegalArgumentException("长度应大于0");
} else {
this.size = size;
this.object = new Object[this.size];
}
}

// Add, Insert, Delete, Find
public void add(Object obj) {
if (obj == null) {
throw new IllegalArgumentException("添加的对象不应为null");
} else {
if (sequence >= size) {
this.size++;// 这里扩展空间方式随意,可以每次扩展两倍
temp = new Object[this.size];
System.arraycopy(object, 0, temp, 0, object.length);
object = temp;
temp = null;
}
object[sequence] = obj;
sequence++;
}

}
public void insert(int index, Object obj) {
if (index < 0 || obj == null) {
throw new IllegalArgumentException("插入的索引值应不小于0,并且插入的对象不应为null");
} else {
if (index == object.length) {
add(obj);
} else if (index > object.length) {
throw new IllegalArgumentException("数据越界,插入的索引不应不在数组范围内");
}
if (sequence >= size) {
this.size++;
}
temp = new Object[this.size];
System.arraycopy(object, 0, temp, 0, index);//[1,2,3]
temp[index] = obj;
System.arraycopy(object, index, temp, index+1, object.length-index);
object = temp;
temp = null;
sequence++;
}

}
public void delete(int index) {
if (index < 0 || index>this.size) {
throw new IllegalArgumentException("索引应在数组范围内");
} else {
temp = new Object[--this.size];
System.arraycopy(object, 0, temp, 0, index);
System.arraycopy(object, index+1, temp, index, object.length-1-index);
object = temp;
temp = null;
sequence--;
}
}

public Object find(int index) {
if (index < 0 || index > this.size) {
throw new IllegalArgumentException("索引应大于0或不大于集合元素数");
} else {
return object[index];
}
}

public int size() {
return this.size;
}

}