[英]Implement ArrayList Class Remove Method Java
我必须实现一个自定义的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)
,然后查看哪一行在异常之前打印。 然后,您只需要弄清楚您要访问哪个索引(它就在标准输出中),然后考虑您要访问的数组有多大。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.