Extending an multidimensional array (2D) in Java
How can I extend a multidimensional array in Java?
I need to extend its first dimension. It's in a format like:
myArray[x][7]
The "开发者_Python百科;7" will stay "7" on all extended parts.
Arrays in Java have fixed length, so you can't really extend it. You will have to create a new, larger, array, and then copy the content of the old array into the new one. Like this:
public class Test {
public static void main(String[] args) {
int[][] myArray = new int[3][7];
// Print first dimension
System.out.println(myArray.length); // prints 3
myArray = addRow(myArray);
// Print first dimension
System.out.println(myArray.length); // prints 4
}
private static int[][] addRow(int[][] previous) {
int prevRowCount = previous.length;
int[][] withExtraRow = new int[prevRowCount + 1][];
System.arraycopy(previous, 0, withExtraRow, 0, previous.length);
withExtraRow[prevRowCount] = new int[] { 1, 2, 3, 4, 5, 6, 7 };
return withExtraRow;
}
}
You could of course also use for instance an ArrayList<SomeType[]>
that grows dynamically. (This is actually the preferred way when dealing with dynamically growing arrays.)
import java.util.*;
public class Test {
public static void main(String[] args) {
List<int[]> myArray = new ArrayList<int[]>();
// Print first dimension
System.out.println(myArray.size()); // prints 0
// Add three rows
myArray.add(new int[] { 1, 2, 3, 4, 5, 6, 7 });
myArray.add(new int[] { 11, 12, 13, 14, 15, 16, 17 });
myArray.add(new int[] { 21, 22, 23, 24, 25, 26, 27 });
// Print first dimension
System.out.println(myArray.size()); // prints 3
}
}
You could also use Arrays.copyOf method, for example:
import java.util.Arrays;
public class Array2D {
public static void main(String[] args) {
int x = 5 //For example
int[][] myArray = [x][7];
myArray = Arrays.copyOf(myArray, myArray.length + 1); //Extending for one
myArray[myArray.length - 1] = new int[]{1, 2, 3, 4, 5, 6, 7};
}
}
if you want to do this, make a class that contains the array as an instance variable and handles all interaction with it.
You can't.
You could create a new array with the correct dimensions, but I would recommend reading up about the ArrayList class which (as far as you need to know) allows for dynamic arrays.
精彩评论