-1
我目前正在学习如何操作通用数组列表。我的教授提供了以下程序的框架,并且作为一种练习方式,我正在尝试填写这些方法。但是,我遇到了与该段的问题:创建一个方法类从通用数组列表中删除元素
public E remove(int index) {
return this.remove((Integer)index); //This is an attempt
}//end remove
它在运行时抛出一个StackOverFlow异常。 下面我有充分的代码(不包括接口和驱动):
package array;
public class DHArrayList<E> implements BareArray<E>{
private int arraySize; // size is an indication of position in array
private int capacity;
private E[] myArray;
private static final int INITIAL_CAPACITY = 10;
//Once you have created an ArrayList, you can ignore the capacity in all programming that follows
public DHArrayList(){
capacity = INITIAL_CAPACITY;
/*INITIAL_CAPACITY is the number of items that ArrayList will allocate to
begin with as the internal storage of items.*/
arraySize = 0;
}//end default constructor
public DHArrayList(int capacity){
this.capacity = capacity;
this.arraySize = 0; //size denotes array indices that are used
myArray = (E[]) new Object[this.capacity];
}//end constructor with parameter
public void add(E a) { //default, will add a value to the end of the list.
if(arraySize < capacity){ //which entails that there exists space
//size value gives the index of first free location
myArray[arraySize] = a;
arraySize++; //updates size
}//end if
else{
System.out.println("Array full. Reallocating . . .");
this.reallocate(); //Change capacity of array
this.add(a);
}//end else
}//end add
private void reallocate(){ // doubles size of array
this.capacity *= 2;
//new array, doubled capacity
E[] newArray = (E[])new Object[this.capacity];
for(int i = 0; i < this.arraySize; i++){
newArray[i] = myArray[i]; // reload values
}//end for
//Reassigns the myArray pointer to the newArray reference point.
this.myArray = newArray;
}//end reallocate
public void add(int index, E a) {
if(index < 0 || index > arraySize){
System.out.println("Invalid index.");
return;
}//end if
/*Reusable code from the add method above,
else-IF index is at end of list.*/
else if(index==arraySize){
this.add(a);
}//end else if
else{
// Ensure there is space, then move elements and insert.
if(this.capacity == this.arraySize) {
this.reallocate();
}//end if
//move data
for (int i = arraySize; i > index; i--){
this.myArray[i] = this.myArray[i-1]; //shifts to right.
}//end for
//Insert data into specified index
this.myArray[index] = a;
arraySize++;
}//end else
}
public E remove(int index) {
return this.remove((Integer)index);
}//end remove
public E get(int index) {
return myArray[index];
}//end get
public void set(int index, E a){
}//end set
public int getSize() {
return 0;
}//end getSize
public int indexOf(E a) {
return 0;
}//end indexOf
public void display(){
System.out.println("The contents of the array are ");
for (int i = 0; i < arraySize; i++) {
System.out.print(this.myArray[i] +", ");
}//end for
}//end display
}//end DHArrayList
你还没有写过任何'remove'方法的实际实现。你必须完成数组中元素的所有移动,等等,你用'add'方法,并确定正确的方法是使用'remove'方法。这会变得很复杂,至少和'add'方法一样复杂。 –
您收到StackOverflow异常,因为您的remove()方法会一遍又一遍地调用自身,直到您超出堆栈空间。否则@LouisWasserman已经提供了答案 – thst