Java 数组nullpointerException错误
这是我的部分代码:Java 数组nullpointerException错误,java,arrays,nullpointerexception,Java,Arrays,Nullpointerexception,这是我的部分代码: `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&a
`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;
}`
repInst的所有位置都为空。我想,如果他把那个“if”放进去,他会跳过它,返回pos=-1
为什么不工作?repInst在构造函数中是局部变量
private Instrumento[] repInst;
public RepositorioInstrumentos(){
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;
}
private Instrumento[]repInst;
公共存储设备(){
repInst=新仪器[20];
}
私有int getPos(int id){
int pos=-1;
对于(int i=0;i初始化构造函数中的repInst
,然后访问它的方法,因为如果在未初始化它的情况下访问它的方法,您将得到NullPointerException
,而tam
变量的值是多少?它的值可能大于数组长度,那么它还将抛出arrayindexoutofboundsXce期权
private Instrumento[] repInst;
public RepositorioInstrumentos(){
repInst = new Instrumento[20];
}
private int getPos(int id){
int pos= -1;
int tam=20;
//tam variable value should b less then arrays length
for(int i=0; i<tam; i++){
if (repInst[i]!=null&&repInst[i].getId()==id){
pos=i;
i=tam;
}
}
return pos;
}`
private Instrumento[]repInst;
公共存储设备(){
repInst=新仪器[20];
}
私有int getPos(int id){
int pos=-1;
int-tam=20;
//tam变量值b应小于数组长度
对于(inti=0;i只需做一个更改。在构造函数外面初始化这个数组
Instrumento[] repInst = new Instrumento[20];
或者用它的对象初始化它。好吧……如果repInst
的所有位置都是null
,那么就不会调用对位置i
中包含的实例实际执行任何操作的逻辑。可能的情况是,自动装箱和null
与getId()有一些乐趣
。tam变量在哪里?为什么在构造函数中初始化新的Arraylist?甚至还没有初始化主变量。
Instrumento[] repInst = new Instrumento[20];