多维ArrayList和Integer替换 [英] Multidimensional ArrayList and Integer replacement

查看:37
本文介绍了多维ArrayList和Integer替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过二维 ArrayList> 和每个 Int 等于 1 你离开它,否则你从它减去 1 .ie if arrayList.get(i).get(j) == 3 现在将是 2 等等,但如果是1 它保持 1) 仅在 ARRAYLIST 的特定列中.

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

推荐答案

拿一把铲子 - 只有一种方法可以做到.遍历所有行中的所有列:

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;
        }
    }
}

如果你有一个 List of List 它看起来像这样:

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);
        }
    }
}

更新:

根据您的编辑,您应该添加要对其执行此转换的数组或列列表.我在第二个代码段中添加了一个示例.

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.

这篇关于多维ArrayList和Integer替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆