papercuts
papercuts

Reputation: 1438

How do I call .get() on a 2d ArrayList

I have a 2d ArrayList

ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();

I want to get the item at say (0,0).

I'm looking for something like:

list.get(0,0)

Thanks!

Upvotes: 5

Views: 55117

Answers (6)

NIKHIL UPADHYAY
NIKHIL UPADHYAY

Reputation: 1

We can use below syntex to fullfill our requirement: arrIJ=arr.get(i).get(j);

I have to find the diagonal difference for the 2D list, where I use the above syntax:

Code of Diagonal Difference in list:

public static int diagonalDifference(**List<List<Integer>> arr**) {
        int size=arr.size();
        int forwardDiagonal=0;
        int backwardDiagonal=0;
        
        for(int i=0;i<size;i++){
            for(int j=0;j<size;j++){
                if(i==j){
                    forwardDiagonal=forwardDiagonal+**arr.get(i).get(j)**;
                }
            }
        }
        
        for(int i=size-1;i>=0;i--){
            for(int j=0;j<size;j++){
                if(i+j==size-1){
                    backwardDiagonal=backwardDiagonal+**arr.get(i).get(j)**;
                }
            }
        }
        return Math.abs(forwardDiagonal-backwardDiagonal);

    }

Upvotes: 0

Aravinth
Aravinth

Reputation: 736

This is a program to traverse the 2D-ArrayList. In this program instead of LineX your can get item in the list (i , j ) :-)

PROGRAM:

Scanner scan = new Scanner(System.in);  
int no_of_rows = scan.nextInt();         //Number of rows 
int no_of_columns = scan.nextInt();      //Number of columns 
ArrayList<ArrayList<String>> list = new ArrayList<>();
for (int i = 0; i < no_of_rows; i++) {      
    list.add(new ArrayList<>());      //For every instance of row create an Arraylist
    for (int j = 0; j < no_of_columns; j++) {
        list.get(i).add(scan.next());        //Specify values for each indices
    }
}
//ArrayList Travesal
for (int i = 0; i < list.size(); i++) {
    for (int j = 0; j < list.get(i).size(); j++) {
        System.out.print(list.get(i).get(j)+" ");   //LineX
    }
    System.out.println();
}

OUTPUT:

2 3 
1 2 3 4 5 6 
1 2 3 
4 5 6

Upvotes: 3

Jeevan Patil
Jeevan Patil

Reputation: 6079

It being List of List, you try :

String val = list.get(0).get(0);

Upvotes: 1

Jack
Jack

Reputation: 133609

You must use

list.get(0).get(0)

since you are not using a real 2-dimensional List but a List of Lists.

Upvotes: 16

Ted Hopp
Ted Hopp

Reputation: 234847

Java doesn't have 2d lists (or arrays, for that matter). Use something like this:

list.get(0).get(0)

Note that arrays have a similar issue. You do not do this:

array[0,0]  // WRONG! This isn't Fortran!

Instead you do this:

array[0][0]

Upvotes: 6

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

As follows

String value = list.get(0).get(0);

Upvotes: 5

Related Questions