我必须实现一个自定义构建的ArrayList类。我们不能使用arrayCopy。我需要能够从数组中删除字符串,然后将所有元素移动到左边一个索引。我的尝试如下,请帮助。
/****************************************************************************
* Removes the string at the specified index from the list,
* if it is present and shifts the remaining elements left.
*
* @param str value to remove from list
* @return the value removed from the list
* @throws IndexOutOfBoundsException if index is invalid
*/
public String remove(int index){
if (index < 0 || index >= this.myArray.length)
{
throw new IndexOutOfBoundsException("Index out of bounds.");
}
else {
String removed = this.myArray[index];
this.myArray[index] = null;
String [] temp = new String[this.myArray.length-1];
for(int i = 0; i<this.myArray.length; i++){
if (this.myArray[i] != null){
temp[i] = this.myArray[i];
}
}
return removed;
}
}
我一直在temp[i] = this.myArray[i]
处得到IndexOutOfBoundsException
您正在创建一个temp
数组,其元素比this.myArray
少一个。然后遍历myArray
的所有索引,并使用这些索引写入temp[i]
。最后一个是越界的,因为temp
比它小一个。
调试器可以帮助你找到这个。您还可以在访问数组的任何行之前放置一个System.out.println("about to access index " + i)
,并查看哪一行正好打印在异常之前。然后你只需要找出你要访问的索引(它就在stdout中)并考虑你要访问的数组有多大
temp
数组较短,因此它不能适合所有内容。
复制数组时需要跳过所需的索引
下面的代码通过为新旧数组中的索引使用两个不同的变量来实现这一点。
当遇到被删除的索引时,它跳过对其中一个进行递增。
public String remove(int index) {
if (index < 0 || index >= this.myArray.length) {
// FYI, this would be thrown anyway; not sure if you need to do it
throw new IndexOutOfBoundsException("Index out of bounds.");
}
String removed = this.myArray[index];
String[] temp = new String[this.myArray.length - 1];
for(int i = 0, j = 0; i < this.myArray.length; i++){
if (i != index) {
temp[j++] = this.myArray[i];
}
// otherwise, j does not get incremented
}
this.myArray = temp; // don't forget this!
return removed;
}