我已经实现了具有泛型类型的SortedLinkedList,但是其中一项任务是制作一个toArray
方法,该方法采用T[]
数组,并用链接列表的元素填充它。为此,我想出了一种get()
方法,该方法会返回该点的Node值,并用这些值填充数组。不幸的是,我遇到了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代码。谢谢!
我所说的单循环是这个伪代码
T array
index = 0
Node node -> point to linked list head
Iterate until node is null:
array[index] = node.element
node -> point to next element
index++