hamid
hamid

Reputation: 2079

Two-Dimensional ArrayList set an element

I have this piece of code:

List<ArrayList<Integer>> tree = new ArrayList<ArrayList<Integer>>();

tree.add(0, new ArrayList<Integer>(Arrays.asList(1)));
tree.add(1, new ArrayList<Integer>(Arrays.asList(2,3)));
tree.add(2, new ArrayList<Integer>(Arrays.asList(4,5,6)));

I would like, for example, to replace 5 with 9. how can I do this?

Upvotes: 5

Views: 13077

Answers (4)

Aman Bhardwaj
Aman Bhardwaj

Reputation: 1

The major methods we use in a 2-Dimensional ArrayList are -->

let say we have a 2-Dimensional ArrayList as

ArrayList<ArrayList<Integer>> ArrayList_2D = new ArrayList<>()

To find the size

ArrayList_2D.size();

To access some element at position (i , j)

ArrayList_2D.get(i).get(j);

To set value of an element at position (i , j) equal to x

ArrayList_2D.get(i).set(j , x);

To remove (i , j) element

ArrayList_2D.get(i).remove(j);

To find the index of first occurring of element y

 int col , row;
 for(int a=0;a<ArrayList_2D.size();a++){
     for(int b=0;b<ArrayList_2D.size();b++){
         if(ArrayList_2D.get(i).get(j)==y){
                 col = i;
                 row = j;
                 break;
         }
     }
 }

Hope This Is Will Be HelpFul

Upvotes: 0

edwga
edwga

Reputation: 190

tree.get(2).set(1, 9)

This gets the third (i.e. index = 2) element of the outer ArrayList, which returns the inner ArrayList. Then set the 2nd element (index = 1) to 9. Autoboxing takes care of the int to Integer conversion.

Upvotes: 2

dantuch
dantuch

Reputation: 9283

find index of elements that you want to replace and use twice set(index, newElement) method to do the replacement

Upvotes: 1

D180
D180

Reputation: 742

use

tree.get(2).set(1,Integer.valueOf(9));

to get the ArrayList at the position 2 and then set the second element to 9.

Upvotes: 12

Related Questions