I am trying to make a 2D array that i can dynamically update. Lets say i have a 2D array with 10 rows and 3 columns. I want to add an int value to a specific row, thereby adding an extra column to that row (and only that row) so that it alone would have 4 columns. Here's what i have so far.
public class DynamicArray {
private int[][] array;
private int size;
public DynamicArray(int initialSize) {
array = new int[10][initialSize];
size = 0;
}
public int get(int j) {
return array[0][j];
}
public int getSize() {
return size;
}
public void put(int N) {
if (size < array[0].length)
array[0][size] = N;
else // need to create a bigger array
{
int[][] temp = new int[10][2 * size];
for (int i = 0; i < array.length; i++)
for (int j = 0; j < array[i].length; j++)
temp[i][j] = array[i][j];
temp[0][size] = N;
array = temp;
}
size = size + 1;
}
public static void main(String[] args) {
DynamicArray da = new DynamicArray(3);
da.put(2);
da.put(1);
da.put(3);
da.put(1);
da.put(4);
da.put(5);
for (int i = 0; i < da.getSize(); i++) {
for (int j = 0; j < 9; j++) {
System.out.print((da.get(i) + "\t"));
}
System.out.println("\n");
}
}
}
The problem is that with this code the program adds the new value to each row instead of only the one specified (in this case row 0). How could I fix this?
Additionally, how could i make the program do the opposite as well -> remove a value from an individual row and shorten that row?