字符串不断初始化为空
问题描述:
我的字符串不断初始化为null ...或者至少看起来像这样。我想为我的矩阵做一个自定义的toString函数。 this.matrixArray
是尺寸'm x n'的二维数组。字符串不断初始化为空
public String toString() {
String stringAsMatrix = "";
String dimensions = this.m + "," + this.n + "\n";
stringAsMatrix += dimensions;
String[] dataRows = new String[this.m];
for (int row = 0; row < this.m; row++) {
for (int column = 0; column < this.n; column++) {
String elementString = "";
elementString += this.matrixArray[row][column];
if (column == this.n-1) {
dataRows[row] += elementString + "\n";
} else {
dataRows[row] += elementString + ","; // Only add a comma if this isn't the last element in the row
}
}
stringAsMatrix += dataRows[row];
}
return stringAsMatrix;
}
这是我得到的输出,但我不明白为什么它会在我的字符串之前打印'null'。尺寸是正确的(矩阵数组的确是2×2)。这些值本身也是正确的(my matrix is {{1,2}, {3,4}})
2,2
null1.0,2.0
null3.0,4.0
答
dataRows[row] += elementString + "\n";
dataRows[row]
开始了与它null
。所以它变成
dataRows[row] = null + elementString + "\n"
......这正是你所得到的。相反,写
dataRows[row] = elementString + "\n";
+0
我很愚蠢。非常感谢您的帮助。 –
当你做一个'新的字符串[this.m]',它开始充满了空值。与任何非原始类型的数组相同。 – user2357112
另外,在循环中用'+ ='构建字符串是一种非常低效的方式。 – user2357112
@ user2357112'+ ='实际上编译为使用'StringBuilder',这在后台有效,可以用'javap -c Classname'看到。 –