Home > Back-end >  how to remove an element from 2d array in java
how to remove an element from 2d array in java

Time:07-04

I want to remove an element after creating the below 2d array.And it should be the last element of the array.

public static void main(String[] args) {
        int i;
        int row = 2;
        int col = 2;
        String[][] queue = new String[row][col];
        Scanner scanner = new Scanner(System.in);
        String[][] queue = new String[row][col];
        Scanner scanner = new Scanner(System.in);
        for (row = 0; row < queue.length; row  ) { // Loop through the rows in the 2D array.
            for (col = 0; col < queue[row].length; col  ) { 
                System.out.println("Enter the name");{
                    queue[row][col] = scanner.next();
                }

                }
            }
        for (i = 0; i < row; i  ) {
            for (int j = 0; j < col; j  ) {
                System.out.print(queue[i][j]   " ");

CodePudding user response:

The question is awkward.

  • You can't "remove" an element from a 2D static array - what you can do is empty that array element. This is as simple as queue[row - 1][col - 1] = "".
  • If you want to be able to remove elements the way you describe, your best choice is use dynamic arrays, such as ArrayList.
  • Note though that Java supports 2D arrays with differing number of columns per row, so you can also create a new array, copy everything except the last column in the last row, and put it back in the original array.

CodePudding user response:

You cannot remove a cell from an array. But you can effectively remove it by simply replacing the last row with a new copy of all but the last element.

queue[row-1] = Arrays.copyOf(queue[row-1], queue[row-1].length-1);

You might want to try creating the array like this. Then you won't need to remove or copy anything.

  • define the Array with the number of rows.
  • then assign the row array separately to the "2D" array. For a large number of rows, this could be done in a loop with an int[] array of dimensions for each row.
int rows = 2;
String[][] queue = new String[rows][];
queue[0] = new String[2];
queue[1] = new String[1];
Scanner scanner = new Scanner(System.in);
for (rows = 0; rows < queue.length; rows  ) { // Loop through the rows in the 2D array.
    for (int col = 0; col < queue[rows].length; col  ) { 
        System.out.println("Enter the name");{
            queue[rows][col] = scanner.next();
        }
    }
}
for (String[] row : queue) {
    System.out.println(Arrays.toString(row));
}
  • Related