【发布时间】:2014-06-24 05:07:39
【问题描述】:
这是我的部分代码:
`private Instrumento[] repInst;
public RepositorioInstrumentos(){
Instrumento[] repInst = new Instrumento[20];
}
private int getPos(int id){
int pos= -1;
for(int i=0; i<tam; i++){
if (repInst[i]!=null&&repInst[i].getId()==id){
pos=i;
i=tam;
}
}
return pos;
}`
我在这一行中不断收到 null Poiter 异常:
`if (repInst[i]!=null&&repInst[i].getId()==id){`
repInst 的所有位置都为空。我认为把那个“如果”他会跳过它并返回 pos = -1。
为什么不工作?
【问题讨论】:
-
嗯...如果
repInst的所有位置都是null,那么实际上对位置i中包含的实例执行任何操作的逻辑将不会被调用。可能的情况是自动装箱和null与getId()有一些乐趣。 -
你的 tam 变量在哪里?
-
为什么要在构造函数中初始化新的 Arraylist?甚至你还没有初始化主要的。
标签: java arrays nullpointerexception