Looks like this is what you want
int columns = 2;
int rows = 2;
String[][] newArray = new String[columns][rows];
newArray[0][0] = "France";
newArray[0][1] = "Blue";
newArray[1][0] = "Ireland";
newArray[1][1] = "Green";
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
System.out.println(newArray[i][j]);
}
}
Here I'll explain the code:
This declares the size of your new 2D array. In Java (and most programming languages), your first value starts at 0, so the size of this array is actually 2 rows by 2 columns
int columns = 2;
int rows = 2;
Here you are using the type String[][] to create a new 2D array with the size defined by [rows][columns].
String[][] newArray = new String[columns][rows];
You assign the values by its placement within the array.
newArray[0][0] = "France";
newArray[0][1] = "Blue";
newArray[1][0] = "Ireland";
newArray[1][1] = "Green";
Looping through i would loop through the rows, and looping through j would loop through the columns. This code loops through all rows and columns and prints out the values in each index.
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
System.out.println(newArray[i][j]);
}
}
Alternatively, assignment can be a one-liner:
String[][] newArray = {{"France", "Blue"}, {"Ireland", "Green"}};
But I don't like this way, as when you start dealing with larger sets of data (like 10,000+ points of data with many columns), hardcoding it in like this can be rough.
Answer from theGreenCabbage on Stack OverflowVideos
You can use the following class which stores your data in a HashMap and is able to convert it to a two dimensional string array.
public class ArrayStructure {
private HashMap<Point, String> map = new HashMap<Point, String>();
private int maxRow = 0;
private int maxColumn = 0;
public ArrayStructure() {
}
public void add(int row, int column, String string) {
map.put(new Point(row, column), string);
maxRow = Math.max(row, maxRow);
maxColumn = Math.max(column, maxColumn);
}
public String[][] toArray() {
String[][] result = new String[maxRow + 1][maxColumn + 1];
for (int row = 0; row <= maxRow; ++row)
for (int column = 0; column <= maxColumn; ++column) {
Point p = new Point(row, column);
result[row][column] = map.containsKey(p) ? map.get(p) : "";
}
return result;
}
}
Example code
public static void main(String[] args) throws IOException {
ArrayStructure s = new ArrayStructure();
s.add(0, 0, "1");
s.add(1, 1, "4");
String[][] data = s.toArray();
for (int i = 0; i < data.length; ++i) {
for (int j = 0; j < data[i].length; ++j)
System.out.print(data[i][j] + " ");
System.out.println();
}
}
Output
1
4
You can simply initialize with a literal, empty two-dimensional array:
String[][] data = new String[][]{{}}