简体   繁体   English

我需要一些帮助来了解实例/引用

[英]I need some help understanding instances/references

Just want to know if what I'm trying to teach myself is right. 只想知道我想教给自己的东西是否正确。

I'll end up with something like this in one of my programs: 我将在其中一个程序中得到如下所示的结果:

public class Test {
    int array[];

    public static void main(String[] args){
        Test test = new Test();
        test.array = new int[10];
        test.fillArray();

        for(int i=0;i<test.array.length;i++)
            System.out.println(test.array[i]);
    }

    public void fillArray(){
        Test test = new Test();
        for(int i=0;i<test.array.length;i++)
            test.array[i]=i;
    }
}

But I get a null pointer exceptions. 但是我得到了一个空指针异常。 I seem to run into these types of issues a decent amount.. Would proper planning of my programs help with this? 我似乎碰到过这类问题。.对我的程序进行适当的计划会对此有所帮助吗?

The null Pointer was because when I say new it creates a separate object that only exists inside that method correct? 空指针是因为当我说new时,它创建了一个仅存在于该方法内部的单独对象对吗?

Are there any other ways to fix this other than making the array static or giving it a parameter (or is it argument..?) like I did below? 除了使数组成为静态数组或为它提供参数(或者是参数..?)之外,还有其他方法可以解决此问题,就像我在下面所做的那样?

public class Test {
    int array[];

    public static void main(String[] args){
        Test test = new Test();
        test.array = new int[10];
        test.fillArray(test.array);

        for(int i=0;i<test.array.length;i++)
            System.out.println(test.array[i]);
    }

    public void fillArray(int a[]){
        for(int i=0;i<a.length;i++)
            a[i]=i;
    }
}

Your first fillArray has a shadowing problem in that you are creating a new test instance and initializing it - instead initialize the field array within the current (or this ) instance, 您的第一个fillArray存在一个阴影问题,因为您正在创建一个新的测试实例并对其进行初始化-而是在当前(或this )实例中初始化字段array

public void fillArray() {
  // Test test = new Test();
  for (int i = 0; i < this.array.length; i++) {
    this.array[i] = i; // <-- this.array or just array[i]
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM