Search code examples
javagenericslinked-listsortedlisttoarray

How to make a generic type T Array for a generic SortedLinkedList?


I have implemented a SortedLinkedList with generic types but one of the assignments is to make a toArraymethod that takes a T[] array and fills it with the elements of the Linked List. For this, I figured I'd make a get()method that returns the value of the Node at that point and fill the array with those values. Unfortunately, I'm hitting IndexOutofBoundsExceptions and I'm not sure where my issue is exactly. If anyone could help, it'd be much appreciated!

My getmethod:

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;
    }

And my toArray method:

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; 
    }

The compiler complains about an OutOfBoundsException at array[i] = this.get(i)and I really don't get why. Any help would be much appreciated, and I'm happy to provide more of the SortedList code if needed. Thanks!


Solution

  • What I mean by single loop was this pseudocode

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