简体   繁体   中英

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

I'm trying to have my method "add" access the contents of an ArrayList that was created in method "Friends", but Java isn't happy with what I'm doing (scope issues?). Is there a way to fix the problem without having to pass arguments?

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]
        }
    }
}

note that Friends is meant to be a constructor (if I'm using that word right)

Obviously for such cases you should use such called "object variables", or simply saying - fields of the class. You should make your variable arrayList part of the class as a field:

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(...).
        }
    }
}

Make your variables member variables of the Friends 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]
        }
    }
}

Your guess is correct. The problem here is scoping. You are creating a local variable arrayList in the constructor, which is only available in the constructor.

You should declare it as an instance variable like this:

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]
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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