vignesh d
vignesh d

Reputation: 305

How to increase the number of rows in a 2d array using java

I need to convert a 2 * 3 array into a 6 * 3 array using java. Any idea how i can do it?I am a novice in Java so any help is appreciated.

Upvotes: 2

Views: 1471

Answers (4)

fge
fge

Reputation: 121720

You can't. Arrays, once allocated, have a fixed size.

You must allocate a new array and copy the contents of the old array into the new one.

One solution is to use Arrays.copyOf() which will take care of the copy for you:

X[][] newArray = Arrays.copyOf(original, 6);
// Necessary: empty spaces are filled with null by default
for (int index = original.length; index < 6; index++)
    newArray[index] = new X[3];

Or go the easy route and use a List instead (an ArrayList as already suggested). They expand on demand.

And if you want a "two-dimensional generic array", Guava has Table out of which you could mimick a two-dimension array using, for instance:

final Table<Integer, Integer, X> mockArray = HashBasedTable.create();

Upvotes: 9

arshajii
arshajii

Reputation: 129507

Arrays are fixed in size. In general, when you need a collection of elements to grow like that, you should use Lists instead of arrays (perhaps an ArrayList, although you should choose the implementation that best suits you). i.e.

X[][]  // fixed number of rows and columns

becomes

List<X[]>  // the number of rows is not fixed anymore

(of course, if you need to change both dimensions, use a List<List<X>>)

Upvotes: 2

0x6C38
0x6C38

Reputation: 7076

Arrays have a fixed size and cannot be changed once allocated in memory. You should use some type of List instead, such as an ArrayList. Their size can be increased or decreased dynamically and you don't even have to set it if you don't want to, you can just add elements without even having to worry about it.

Upvotes: 1

stinepike
stinepike

Reputation: 54682

you can't change the size of an array. but, you can create a new array that has the dimension 6 * 3, copy the data over (System.arrayCopy, Arrays.copyOf), and return a reference to your new array.

If you are not sure initially about the array size use ArrayList Instead.

Upvotes: 3

Related Questions