我正在尝试初始化一个二维数组(我创建的类对象),但我一直遇到相同的运行时错误:
Exception in thread "main" java.lang.NullPoointerException
at ........
我已经设法用原始类型来做到这一点,而不是扩展对象的类型,我想知道这是否可能(如果是这样的话)。
这是我的代码示例:
MyCustomObject[][] matrix = new MyCustomObject[10][10];
for (int i = 0; i < 10; i += 1)
matrix[i][0] = new MyCustomObject("some arguments ...");
错误标记在我尝试为矩阵赋值的行中:matrix[i][0] = ....
根据我研究后的理解,Java 为数组的每个成员都赋予了 null 值,这对我来说是可以的。但是为什么当我尝试用现有值替换空值时它会标记我一个错误。我不是在 null 上调用方法。
完整代码:
int sourceLength = source.length(); // Length of a CharSequence
int targetLength = target.length(); // Length of a CharSequence
Matrix distanceMatrix[][] = new Matrix[sourceLength][targetLength];
for (int row = 1; row < sourceLength; row += 1) {
distanceMatrix[row][0] = new Matrix( // The error is marked at this line.
distanceMatrix[row - 1][0].cost + option.getDeletionCost(),
row - 1,
0
);
}
for (int column = 1; column < targetLength; column += 1) {
distanceMatrix[0][column] = new Matrix(
distanceMatrix[0][column - 1].cost + option.getInsertionCost(),
0,
column - 1
);
}
for (int row = 1; row < sourceLength; row += 1) {
for (int column = 1; column < targetLength; column += 1) {
// do more stuff.
}
}
矩阵类(在主类中):
public final static class Matrix {
public int cost;
public int row;
public int column;
public Matrix(int cost, int row, int column) {
this.cost = cost;
this.row = row;
this.column = column;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Matrix)
return (cost == ((Matrix)obj).cost
&& row == ((Matrix)obj).row
&& column == ((Matrix)obj).column);
return (super.equals(obj));
}
}
堆栈跟踪:
Exception in thread "main" java.lang.NullPointerException
at net.azzerial.gt.core.Fuzzy.distance(Fuzzy.java:54)
at net.azzerial.gt.core.Fuzzy.levenshteinDistance(Fuzzy.java:24)
at net.azzerial.gt.Test.main(Test.java:15)
Matrix distanceMatrix[][] = new Matrix[sourceLength][targetLength];
for (int row = 1; row < sourceLength; row += 1) {
distanceMatrix[row][0] = new Matrix( // The error is marked at this line.
distanceMatrix[row - 1][0].cost + option.getDeletionCost(), //actually it occurs here
row - 1,
0
);
}
问题是当您尝试调用distanceMatrix[row - 1][0].cost
和 时row==1
。您从未创建过 distanceMatrix[0][0],它为空,并且您尝试访问它的成本字段。我假设该option
对象不为空(也值得检查)。
如果单个方法调用只有几行长,则堆栈跟踪将指向调用开始的行。例如,new Matrix()
调用从第 54 行开始并在第 58 行结束,错误发生在第 55 行,但堆栈跟踪指向第 54 行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句