Search code examples
javalistgenericsrecursiongeneric-list

Prepend function of my recursive list creates an endless list


Currently, I'm working on a generic list in Java. Problem: The prepend method doesn't work the way it should. Instead of adding an element T at index 0 it's creating an endless recursive list.

public class Vector<T>{

    private T value;
    private Vector<T> next = null;

    public Vector(T value){
        this.value = value;
    }

    public Vector(T value, Vector<T> next){
        this.value = value;
        this.next = next;
    }

    public void prepend(T element){
        this.next = this;
        this.value = element;
    }
}



public class Main{
    ...
    Vector<Integer> v1 = new Vector<Integer>(new Integer(1));
    v1.prepend(new Integer(0));
    ...

Expected output: {0,1} Actual output: {0,0,0,0,0,0,0, ........ }


Solution

  • What you are doing: First, you create a Vector with value = 1, next = null. „Prepending“ 0, you set next to this, an endless recursion, then you set value = 0. If you look at your Vector, you first get the value = 0. Then you change to the Vector next, which still is this. Of that „new“ Vector, you output value = 0. Then you change to the Vector next, which still is this. Of that „new“ Vector, you output value = 0. Then ... you get it.

    What you most probably want to do: When prepending an Integer, you want to COPY this to next and set value to the new Integer. That would read:

    public class Vector<T>{
    
    […]
        public void prepend(T element){
            this.next = new Vector<>(value, next); // a Copy Constructor would also be fine
            this.value = element;
        }
    }