简体   繁体   中英

Remove 0 Index of every inner array of 2D Array

I try to solve this, but i don't come further. I have an 2D int Array and want to remove the first index of every index like this: {{1,2}, {2,3,4}} -> {{2}, {3,4}}

I worked on this code but it doesn't change anything.

int[][] arr = {{1,2},{2,3,4}};

    for(int[] x : arr) {
        int[] newArr = new int[x.length -1];
        for (int i = 1; i < x.length; i++) {
            newArr[i-1] = x[i];
        }

        x = newArr;
    }

I'm grateful for your help.

You can do it as follows:

public class Main {
    public static void main(String[] args) {
        int[][] arr = { { 1, 2 }, { 2, 3, 4 } };

        for (int i = 0; i < arr.length; i++) {
            int[] newArr = new int[arr[i].length - 1];
            for (int j = 1; j < arr[i].length; j++) {
                newArr[j - 1] = arr[i][j];
            }
            arr[i] = newArr;
        }

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output:

2 
3 4 

Are you sure it's not working? I ran this and it worked for me. Maybe you are assigning the wrong array at the end to the array that you want it to go to? Make sure you assign whatever array that you care about to newArr after the loops.

Don't use enhanced for loop, and use Arrays.copyOfRange(...) :

int[][] arr = {{1,2},{2,3,4}};
for (int i = 0; i < arr.length; i++)
    arr[i] = Arrays.copyOfRange(arr[i], 1, arr[i].length);
System.out.println(Arrays.deepToString(arr));

Output

[[2], [3, 4]]

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