在不传递参数的情况下从相同 class 中的其他方法访问 ArrayList 的方法?

Way to access ArrayList from other method in same class without passing argument?

我试图让我的方法 "add" 访问在方法 "Friends" 中创建的 ArrayList 的内容,但 Java 对我的行为不满意做(范围问题?)。有没有无需传递参数即可解决问题的方法?

public class Friends {
public Friends(float x, float y)
    {       
        ArrayList<MyObject> arrayList = new ArrayList<MyObject>(); 
        MyObject[] friendList = new MyObject[20];

    }

public void add()
    {       
        for (int i = 0; i < 20; i++) {
            //friendList[i]
        }
    }
}

请注意,Friends 是一个构造函数(如果我没用错的话)

显然,对于这种情况,您应该使用所谓的 "object variables",或者简单地说 - class 的字段。您应该将变量 arrayList 作为字段 class 的一部分:

public class Friends {
List<MyObject> arrayList;
public Friends(float x, float y)
    {       
        arrayList = new ArrayList<MyObject>(); 
        MyObject[] friendList = new MyObject[20];

    }

public void add()
    {       
        for (int i = 0; i < 20; i++) {
            //arrayList.add(...).
        }
    }
}

让你的变量朋友的成员变量class:

public class Friends {
ArrayList<MyObject> arrayList;
MyObject[] friendList;
public Friends(float x, float y)
    {       
        arrayList = new ArrayList<MyObject>(); 
        friendList = new MyObject[20];

    }

public void add()
    {       
        for (int i = 0; i < 20; i++) {
            //friendList[i]
        }
    }
}

你猜对了。这里的问题是范围界定。您正在构造函数中创建一个局部变量 arrayList,该变量仅在构造函数中可用。

您应该将其声明为实例变量,如下所示:

public class Friends {

    ArrayList<MyObject> arrayList; = new ArrayList<MyObject>(); 
    MyObject[] friendList; = new MyObject[20];

    public Friends(float x, float y)
    {       
        this.arrayList = new ArrayList<MyObject>(); 
        this.friendList = new MyObject[20];
    }

public void add()
{       
    for (int i = 0; i < 20; i++) {
        //friendList[i]
    }
}

}