still_learning
still_learning

Reputation: 25

how do I access the first and last row of an arraylist of arraylist

I was wondering how I could access the first and last row of this 2d arraylist.

public static ArrayList<Integer> list(ArrayList<ArrayList<Integer>> grid){

    ArrayList<Integer> num = new ArrayList<>();

    for(int i = 0; i < grid.size(); i++){
        for( int j = 0; j <grid.get(i).size(); j++){
            System.out.print(grid.get(i).get(j) + " ");
        }
        System.out.println();
    }

this code will print out the entire arraylist. Is there a way to get the first row and last row only

3 4 1 2 8 6

6 1 8 2 7 4

5 4 3 9 9 5

5 9 8 3 2 6

8 7 2 9 6 4

Upvotes: 0

Views: 90

Answers (1)

Jhanzaib Humayun
Jhanzaib Humayun

Reputation: 1183

grid.get(0) gives you the first row, and grid.get(grid.size()-1) gives you the last row.

If you want to print them out then do this:

public static ArrayList<Integer> list(ArrayList<ArrayList<Integer>> grid){
ArrayList<Integer> num = new ArrayList<>();

int[] firstLastIndices = new int[]{0, grid.size()-1}
for(int i : firstLastIndices){
    for( int j = 0; j <grid.get(i).size(); j++){
        System.out.print(grid.get(i).get(j) + " ");
    }
    System.out.println();
}

Upvotes: 1

Related Questions