【发布时间】:2019-12-09 19:37:37
【问题描述】:
我已经实现了一个具有泛型类型的 SortedLinkedList,但其中一项任务是创建一个 toArray 方法,该方法采用一个 T[] 数组并用链接列表的元素填充它。为此,我想我会创建一个get()method,它返回该节点的值并用这些值填充数组。不幸的是,我遇到了 IndexOutofBoundsExceptions,我不确定我的问题到底出在哪里。如果有人可以提供帮助,将不胜感激!
我的get方法:
public T get(int i) throws IndexOutOfBoundsException {
Node<T> n = head;
if (i < 0)
throw new IndexOutOfBoundsException();
if(i==0)
return head.element;
while(n != null && i > 0){
n = n.next;
i--;
}
if (n == null)
throw new IndexOutOfBoundsException();
return n.element;
}
还有我的toArray 方法:
public T[] toArray(T[] array){
int len = this.size();
//T[] copy = (T[]) new Comparable[len];
for (int i = 0; i < len; i++){
array[i] = this.get(i);
}
return array;
}
编译器在 array[i] = this.get(i) 处抱怨 OutOfBoundsException,我真的不明白为什么。任何帮助将不胜感激,如果需要,我很乐意提供更多 SortedList 代码。谢谢!
【问题讨论】:
-
您编写了几行代码,在
get中抛出 IndexOutOfBoundsExceptions。看起来你正在击中一个。 -
调试应该很容易找到问题。哪一行抛出异常?您没有检查数组大小。可能是数组比列表小,当你尝试分配一些东西时它失败了?
-
在
while循环中,您有终止条件n != null因此,当循环完成时,您将获得OutOfBoundsException。 -
更简单的方法是创建一个带有变量的循环来跟踪数组索引。
-
@alex 甚至删除了
if(n == null)exception,代码给了我同样的错误。而且我不太明白你用一个循环来跟踪索引的意思?你的意思是把整个get方法放在一个while 循环中?
标签: java generics linked-list sortedlist toarray