创建一个类的实例?

时间:2013-11-05 22:43:01

标签: java object treemap

我一直收到下面指出的错误。我假设我没有正确宣布:

public class SparseMatrix {

// instance variables 
private final TreeMap<Integer,TreeMap<Integer,Double>> matrix;
private final int rows;
private final int cols;

public SparseMatrix(int r, int c) {
              // this gives me an error
    this.rows = new SparseMatrix(r);
    this.cols = new SparseMatrix(c);

} // end of constructor
}

3 个答案:

答案 0 :(得分:1)

您没有SparseMatrix的构造函数,它只接受一个int参数。此外,this.rowsthis.colsint个值,而不是SparseMatrix个字段。此外,您需要在构造函数中初始化final字段matrix。你可能想要这个:

public class SparseMatrix {

    // instance variables 
    private final TreeMap<Integer,TreeMap<Integer,Double>> matrix;
    private final int rows;
    private final int cols;

    public SparseMatrix(int r, int c) {
        this.rows = r;
        this.cols = c;
        this.matrix = new TreeMap<>();
    } // end of constructor

}

答案 1 :(得分:0)

矩阵是最终的,因此需要在其声明或构造函数中声明。删除最后一个,你应该编译好,虽然你需要在某些时候初始化矩阵,如果你想使用它。

行和列也可以是整数,但是您要分配SparseMatric对象

我怀疑你想要像

这样的东西
private TreeMap<Integer,TreeMap<Integer,Double>> matrix;
private final int rows;
private final int cols;

public SparseMatrix(int r, int c) {
  this.rows = r;
  this.cols = c;
} 

然后你会以某种方式在矩阵中使用行和列。有了更多信息,我们可以提供更多帮助;)

答案 2 :(得分:0)

this.rowsthis.col属于类型 int,但您尝试将它们实例化为SparseMatrix。您无条件地在SparseMatrix内实例化SparseMatrix也存在问题。想想那个循环何时终止......