Multidimensional ArrayList and Integer replacement

2019-08-20 04:01发布

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>>.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-20 04:38

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.

查看更多
Deceive 欺骗
3楼-- · 2019-08-20 04:47

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;         
    } 
}
查看更多
登录 后发表回答