What is the best (or anyway, really) of going through a bi-dimensional ArrayList<ArrayList<Integer>>
and for every Int
that is equal to 1
you leave it, otherwise you subtract 1
from it.
i.e. if arrayList.get(i).get(j) == 3
it will now be 2
and so forth, but if it is 1
it stays 1
) Only in specific columns of the ARRAYLIST<ARRAYLIST<INTEGER>>
.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Get a shovel - there's just one way to do it. Iterate over all the columns in all the rows:
// example declaration only - initially all zeros until you set them.
// assumes nrows and ncols are initialized and declared elsewhere
int [][] matrix = new int[nrows][ncols];
for (int i = 0; i < matrix.length; ++i) {
for (int j = 0; j < matrix[i].length; ++j) {
// operate on the values here.
if (matrix[i][j] != 1) {
matrix[i][j] -= 1;
}
}
}
If you've got an List of List it looks like this:
List<List<Integer>> matrix = new ArrayList<List<Integer>>();
List<Integer> columnIdsToTransform = Arrays.asList({0, 4, 6 });
// You have to initialize the references; all are null right now.
for (List<Integer> row : matrix) {
for (int j = 0; j < row.size(); ++j) {
// operate on the values here.
value = row.get(j);
if (columnsIdsToTransform.contains(j) && (value != 1)) {
row.set(value-1, j);
}
}
}
UPDATE:
Based on your edit, you should add an array or List of columns you want to perform this transformation on. I've added an example to the second snippet.
回答2:
Iterate through all the values and use your conditional statement for performing the operation on the true
cases.
for (int i=0;i<Arraylist.size();i++) {
for (int j=0;j<Arraylist[i].size();j++) {
if (arrayList.get(i).get(j) != 1)
arrayList.get(i).get(j) -= 1;
}
}