【问题标题】:Array nullpointerException ERROR数组 nullpointerException 错误
【发布时间】: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 中包含的实例执行任何操作的逻辑将不会被调用。可能的情况是自动装箱和nullgetId() 有一些乐趣。
  • 你的 tam 变量在哪里?
  • 为什么要在构造函数中初始化新的 Arraylist?甚至你还没有初始化主要的。

标签: java arrays nullpointerexception


【解决方案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;
}

【讨论】:

    【解决方案2】:

    在构造函数中初始化repInst,然后访问它的方法,因为如果你访问它的方法而不初始化它,你会得到NullPointerException,而tam变量的值可能是它的值大于数组长度然后它也会抛出ArrayIndexOutOfBoundsException

    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;
    }`
    

    【讨论】:

      【解决方案3】:

      只需做一个改变。在构造函数之外初始化你的这个数组。

      Instrumento[] repInst = new Instrumento[20];
      

      或者用那个对象初始化它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多