0

I am developing a game for android this game reads an int[] array and forms a map out of it

now I want to randomly add smaller arrays to this array but how can I do that I don't have any clue

I have searched here and I didn't find a good solution

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
user1293780
  • 63
  • 3
  • 10
  • Do you mean you want to append the smaller arrays to the end of the map array, or copy them into the map array at a random offset? – ravuya Apr 08 '12 at 18:42
  • The proper term to search is, perhaps, "How-to concatenate Java arrays" and proper solution could be found here, I guess: http://stackoverflow.com/questions/80476/how-to-concatenate-two-arrays-in-java If you play with the indexes, you can insert the second array to a different position, not only append it at the end. – Jiri Patera Apr 08 '12 at 19:04

3 Answers3

1

If you need to do it many times arrays are not a good choice, because they have fixed size and must be reallocated every time you increase their size. In addition you have to copy values from the old array to the new, bigger, one.

Take a look to ArrayList<Integer> instead.

If it's something you do just from time to time you should do something like the following

int[] oldArray = new int[Y];
int[] smallArray = new int[X];
int[] newArray = Arrays.copyOf(oldArray,X+Y);
for (int i = Y; i < X+Y; ++i)
  newArray[i] = smallArray[i-Y];
Jack
  • 131,802
  • 30
  • 241
  • 343
0

In Java array does not change in size. You have to create new bigger/smaller one and copy data. This may help.

Alex
  • 4,457
  • 2
  • 20
  • 59
0

you can use

Vector<String> vec = new Vector<String>();
vec.add("a");
vec.add("b);

suppose this is your old vector(or array) with two data.

if you want to add more data or want to add another array then.

for(int i=0;i<arr.length;i++)
{
    vec.add(arr[i]);
}

you can also get length of vector using

    int i=vec.size();
MAC
  • 15,799
  • 8
  • 54
  • 95