【问题标题】:How to make a generic type T Array for a generic SortedLinkedList?如何为泛型 SortedLinkedList 创建泛型类型 T 数组?
【发布时间】: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


【解决方案1】:

我所说的单循环是这个伪代码

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++

【讨论】:

  • 你的伪代码没问题,我按照你的建议做了循环。但是如果我在我的主要方法中要求list.get(0),OutOfBoundsException 仍然会弹出。它说unreported exception IndexOutOfBoundsException; must be caught or declared to be thrown - 所以问题也在我的get方法中。
  • 好的,感谢您的帮助,我得到了正确答案,这是在您的伪代码的帮助下,非常感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多