【问题标题】:How can I write a default constructor for a 1x1 matrix with an ArrayList (in Java)?如何使用 ArrayList(Java 中)为 1x1 矩阵编写默认构造函数?
【发布时间】:2014-09-03 18:05:48
【问题描述】:

为了更清楚,1x1 矩阵需要有一个 false 值。每个矩阵行都是ArrayList<Boolean> 类型的对象。那么整个矩阵就是这些对象的ArrayList。换句话说,矩阵是ArrayList<ArrayList<Boolean>> 类型的对象。

就像在 C 中一样

 Container = new ArrayList()
 Container.add(new ArrayList<>)[arrayList<Boolean>()]
 Container[0].add($false)

或类似的东西。我只是对如何在 Java 中编写类似的构造函数感到困惑。

【问题讨论】:

  • C中没有构造函数,也没有new关键字。
  • 你为什么把这个问题标记为 c ?
  • 从C什么时候开始支持Bool数据类型的?

标签: java matrix arraylist


【解决方案1】:

对于nRows x nCols 矩阵:

ArrayList<ArrayList<Boolean>> matrix = new ArrayList<>(nRows);
for(int r = 0 ; r < nRows ; r++) {
    ArrayList<Boolean> row = new ArrayList<>(nCols);
    for(int c = 0 ; c < nCols ; c++) {
        row.add(false);
    }
    matrix.add(row);
}

对于1 x 1

ArrayList<ArrayList<Boolean>> matrix = new ArrayList<>(1);
ArrayList<Boolean> row = new ArrayList<>(1);
row.add(false);
matrix.add(row);

【讨论】:

    【解决方案2】:

    这将创建一个 n x n 矩阵:

        ArrayList<ArrayList<boolean>> matrix = new ArrayList<ArrayList<boolean>>(n);
        for(int i = 0; i < n; i++) {
            ArrayList<boolean> row = new ArrayList<boolean>(n);
            for(int j = 0; j < n; j++) {
               row.add(false);
            }
            lists.add(row);
        }
    

    【讨论】:

      【解决方案3】:

      具有 n x m 构造函数的示例 Matrix 类:

      public class Matrix extends ArrayList<ArrayList<Boolean>> {
      
          private static final long serialVersionUID = 1L;
      
          public Matrix(int rowNum, int colNum) {
              super(rowNum);
      
              for (int row=0; row<rowNum; row++) {
                  ArrayList<Boolean> rowList = new ArrayList<Boolean>(colNum);
                  add(rowList);
                  for (int col=0; col<colNum; col++) {
                      rowList.add(false);
                  }
              }
          }
      
          public void set(int row, int col, Boolean value) {
              get(row).set(col, value);
          }
      
          public Boolean get(int row, int col) {
              return get(row).get(col);
          }
      
      }
      

      【讨论】:

      • 你不需要检查边界,只需让ArrayList中的get抛出ArrayOutOfBoundException
      • @Jean Logeart:已删除。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      • 2017-03-02
      • 2017-07-15
      • 2013-06-08
      • 2015-06-26
      • 1970-01-01
      相关资源
      最近更新 更多