Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two-Dimensional ArrayList set an element

Tags:

java

arraylist

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?

like image 305
Hamid Avatar asked Apr 06 '13 19:04

Hamid


3 Answers

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.

like image 159
D180 Avatar answered Nov 02 '22 23:11

D180


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.

like image 27
edwga Avatar answered Nov 03 '22 00:11

edwga


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

like image 28
dantuch Avatar answered Nov 03 '22 00:11

dantuch