1

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)

1
  • 1
    friendList should be a instance field instead of a local variable in the constructor Commented Nov 7, 2015 at 20:18

3 Answers 3

4

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(...).
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

}

2 Comments

"Global" is misleading. It's an instance or member variable.
You're absolutely right I changed it to instance variable. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.