0

I was using the LinkedList class in java as a guide for writing my own doubly linked list (this is for school). In this toArray method:

        public <T> T[] toArray(T[] a) {
        if (a.length < size)
            a = (T[])java.lang.reflect.Array.newInstance(
                                a.getClass().getComponentType(), size);
        int i = 0;
        Object[] result = a;
        for (Node<E> x = first; x != null; x = x.next)
            result[i++] = x.item;

        if (a.length > size)
            a[size] = null;

        return a;
    }

It seems to me that it is returning the wrong variable. I assumed it would return result but instead it returns a. Is there something I'm missing where filling result with the items also affects the values in a or am I correct that it is result that should be returned?

Josh314151
  • 66
  • 1
  • 10
  • 2
    The variables `a` and `result` each point to the same object. But `a` is of type `T[]`. If you return `result`, you will get a compile time error. – WJS Jun 09 '22 at 22:44
  • This method from class `LinkedList` uses special tricks / advanced Java techniques that have to do with generics (too complicated to explain quickly) and if this is for a school assignment, it's probably not a good and simple example of a method to look at. – Jesper Jun 09 '22 at 23:53
  • Thanks @WJS, I think I get why it works now and why it was done that way. I always mix up how pointers work in Java (I'm more used to python). – Josh314151 Jun 10 '22 at 02:29
  • Also, @Jesper, it's for a school assignment but for a master's level course. Don't assume that for school == low level. In this case the assignment is to create a doubly linked list by implementing the Deque interface and this was one of the methods that had to be implemented as a consequence of implementing that interface. – Josh314151 Jun 10 '22 at 02:30

0 Answers0