0

I have a problem where I'm supposed to expand an array, each time creating an array with identical results. Before you tell me to just use ArrayList or something else already in the Java API, I was specifically instructed to use my own code. I tried simply creating an array that is one slot larger than my current array, though that does not seem to work very well. Here is what I have that the current moment:

public static void expand(Object[] objArray) {
    Object[] objArray2 = new Object[a.length + 1];
    for (int i = 0; i < a.length; i++)
        objArray[i] = objArray[i];
    objArray = objArray2;
}
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199

5 Answers5

3

You can't update the caller's reference inside the function. Instead, you need to return your new Object[] and update in the caller. Also, you could use System.arraycopy()

public static Object[] expand(Object[] a) {
    Object[] b = new Object[a.length + 1];
    System.arraycopy(a, 0, b, 0, a.length);
    return b;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
3

I Java, arrays are objects and objects are passed by value to methods, and that is, if you change what the reference is pointing to in the method, your changes will stay locally. The solution is to return the modified object

 public static Object[] expand(Object[] objArray) {
   Object[] objArray2 = new Object[a.length + 1];
   ..
   return objArray2;
 }
Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
0

objArray is just a passed in reference argument to the method. It will not change external reference variables. The variable objArray is removed from the stack the moment the method is ended.

Stewart
  • 17,616
  • 8
  • 52
  • 80
0

Assigning to a parameter has no affect on the matching argument, as opposed to modifying a parameter, which does.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Oh dear, where to start.

  • This method is void and doesn't throw or side-effect, therefore it does nothing.

  • The statement objArray[i] = objArray[i]; has no effect.

  • a is not declared (or you haven't shown us enough context).

Chris Martin
  • 30,334
  • 10
  • 78
  • 137