1

If a method is passed a reference to an array, is there any way to alter the size of that array so that the array reference that was passed in will refer to the new, larger array?

I don't entirely understand the question. I think it means that I will ultimately have to create a new string in the method that replaces the old one. Any Help will be appreciated. This is my code thus far:

import java.util.Arrays;

public class ASize {
    static int num[] = {32, 34, 45, 64};
    public static void main(String[] args){


        alterThatSize(num);
            System.out.println(Arrays.toString(num));
    }

    public static void alterThatSize(int bre[]){
        for(int i = 0; i < 8; i++){
        bre[i] = 1 + i; 
        }

        }

}
userb
  • 173
  • 2
  • 15
  • you'll need to create a new array, with the size of oldArray+1, then copy the old one to the new one – yarivt May 23 '15 at 03:17
  • create a new array in the second method? and how do I copy? – userb May 23 '15 at 03:18
  • your question is not clear enough, what exactly are you trying to do? – yarivt May 23 '15 at 03:20
  • if you create a new array `bre` in your method, you have to use `num = bre` to copy it to `num` at the end – kaykay May 23 '15 at 03:23
  • when you said create a new array, did you mean in the "public static void alterThatSize(...)" method or create new array in the main method? Also, I've been trying to copy num[] using .copyOf() and It's not working, so how is it done? – userb May 23 '15 at 03:23
  • You don't get IndexOutOfBoundsException in alterThatSize? – Suspended May 23 '15 at 03:33
  • Yes. I am going to use the code below. – userb May 23 '15 at 03:42

1 Answers1

2

It's not possible to do this because of two reasons. First, Java arrays have fixed length which cannot be changed since array is created. Second, Java is pass-by-value language, so you cannot replace the passed reference with the reference to the new array. Usually such task is solved by using the return value:

static int[] expandArray(int[] arr, int newSize) {
    int[] newArr = new int[newSize];
    System.arraycopy(arr, 0, newArr, 0, arr.length);
    return newArr;
}

Use it like this:

num = expandArray(num, newSize);
Community
  • 1
  • 1
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • That's right, if you want flexible size in array you need to use ArrayList. – MaxZoom May 23 '15 at 03:29
  • 1
    I got it. But for the actual question, is that the answer? you can't alter the size of that array so that the array reference that was passed in will refer to the new, larger array? – userb May 23 '15 at 04:00