0

I'm trying to create a node which contains a int array thats size is determined by an int value taken as a parameter, this is what I have so far. It works fairly well but when I go to fill it it will take arrays of any size which is not what I want. thank you.

public Node(int size, int [] contents, Node<T> t) {
    size = size;
    intArray = new int[size];
    intArray = contents;
    tail = t;
  }
  • You need to remove `intArray = contents;`Loop through `contents` array and set value in your `intArray` – Raghav Nov 13 '16 at 20:06
  • Don't assign contents to intArray. Use System.arraycopy to copy the contents. Also verify that array sizes match before copying. – Quagaar Nov 13 '16 at 20:07
  • 1
    You can also use System.arraycopy() instead of looping over the array. http://stackoverflow.com/questions/5785745/make-copy-of-array-java – Patrick Nov 13 '16 at 20:07

1 Answers1

0

So here...

intArray = new int[size];
intArray = contents;

You are first initializing the array variable to an array of the size you want, but then you are re-assigning the array variable to the array passed in as an argument. You will need to copy or truncate the passed in array somehow.

Take a look at [System.arraycopy][1]. You could do something like...

intArray = new int[size];
System.arraycopy(contents, 0, intArray, 0, size);
Drew Wills
  • 8,408
  • 4
  • 29
  • 40