简体   繁体   中英

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.

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();

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.

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

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>> )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM