【问题标题】:Multidimensional ArrayList and Integer replacement多维 ArrayList 和整数替换
【发布时间】:2012-02-01 02:00:04
【问题描述】:

什么是最好的(或者无论如何,真的),通过二维 ArrayList<ArrayList<Integer>> 并且对于每个等于 1Int,你留下它,否则你减去1 来自它。 if arrayList.get(i).get(j) == 3 现在将是 2 等等,但如果是 1 它保持在 1) 仅在 ARRAYLIST<ARRAYLIST<INTEGER>> 的特定列中。

【问题讨论】:

    标签: java arrays get arraylist


    【解决方案1】:

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

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

    更新:

    根据您的编辑,您应该添加要执行此转换的数组或列列表。我在第二个 sn-p 中添加了一个示例。

    【讨论】:

    • 抱歉,duffymo 刚刚编辑了这个问题,因为我在发布它时显然是脑残,不过,谢谢!
    【解决方案2】:

    遍历所有值并使用条件语句对true 案例执行操作。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      相关资源
      最近更新 更多