Home > Net >  <T> T[] toArray(T[] array) not modifying the original array
<T> T[] toArray(T[] array) not modifying the original array

Time:11-15

I've written the following code as an implementation for a BST. Added toArray() simply for reference. The returning array works perfectly fine, but it won't modify the original one after running the method. I'm not sure if there's something wrong with it or if it's working as intended. Any suggestions?

@Override
public Object[] toArray() {
    Object[] array = new Object[size];
    ArrayList <TreeNode<E>> list = new ArrayList<>();
    toArray(root, list);
    for (int i = 0; i < size; i   ){
        array[i] = list.get(i);
    }
    return array;
}

protected void toArray(TreeNode<E> root, ArrayList <TreeNode<E>> array){
    if (root == null) return;
    toArray(root.left, array);
    array.add(root);
    toArray(root.right, array);
}

@Override
public <T> T[] toArray(T[] array) {
    if (size > array.length){
        array = (T[]) Array.newInstance(toArray()[0].getClass(), size);
    }
    if (size >= 0) System.arraycopy(toArray(), 0, array, 0, size);
    return array;
}

CodePudding user response:

Java will NEVER replace the method argument with something else.

That's just the way the language is designed to work. So yes, it's working as it should, even if maybe not as expected by you.

You're basically confusing yourself by your "array = ..." line. Better to create an array with a new name rather than trying to reuse the name.

That's why many people (me included) recommend very strongly to declare all method arguments as "final", as then the compiler would alert you about it (apart from that it does little).

  • Related