问题
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?
回答1:
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.
回答2:
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.
回答3:
find index of elements that you want to replace and use twice set(index, newElement) method to do the replacement
来源:https://stackoverflow.com/questions/15855154/two-dimensional-arraylist-set-an-element