0

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

6
  • What values do i and j have while the first row is being printed? What values do they have while the last row is being printed? You can either add more print calls, or use the debugger to answer that question. Commented Mar 20, 2022 at 6:17
  • And what do you mean by "get"? Commented Mar 20, 2022 at 6:18
  • sorry for the confusion, I mean to either print the first row only [3 4 1 2 8 6], or print the last row[8 7 2 9 6 4]. Commented Mar 20, 2022 at 6:21
  • I just figure out how to print the first row. Any thoughts on how to print just the last row? Commented Mar 20, 2022 at 6:27
  • You already know how to get the number of rows. And you know that the final index is one less than that. Commented Mar 20, 2022 at 6:31

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.