Nick Nick - 7 months ago 10
Java Question

Creating a method that returns an array of all items in a set (linked list)

I've been trying to find the solution to the errors I'm getting for this method:

public Object[] toArray() {
int size = 1;
Node curr = head;

while (curr.getNext() != null) {
size++;
curr = curr.getNext();
}

Object[] arr = new Object[size];
arr[0] = head.getItem();

curr = head;

for (int i = 1; i < size; i++) {
arr[i] = curr.getNext().getItem();
}
return arr;
}


The goal of the method is to simply return an object array of all the items in the set. This method is part of my class, "Set", which is a child class of my "LinkedList" class, which gives me access to the instance variable head. The method will take my list and add the first element, and second element to the array, and then instead of continuing on to the third, fourth, etc. it simply populates the rest of the array with the second element in my list.

Could anyone give me some advice? Thank you!

Answer

Try this:

public Object[] toArray() {
        int size = 1;
        Node curr = head;

        while (curr.getNext() != null) {
            size++;
            curr = curr.getNext();
        }

        Object[] arr = new Object[size];
        //arr[0] = head; // Shouldn't be arr[0] = head.getItem(); ???
        arr[0] = head.getItem();

        Node curr = head; // You should set curr to head;

        for (int i = 1; i < size; i++) {
            arr[i] = curr.getNext().getItem();
            curr = curr.getNext(); // Otherwise you can't go to next element;
        }
        return arr;
    }