Hat_To_The_Back
Hat_To_The_Back

Reputation: 43

Allow an ArrayList to be used in different classes

If I create a class that reads text into an ArrayList. How do I access this ArrayList in other classes? What do I declare the ArrayList as in the class?

Then when I want a different class to access it, how do I go about doing that? I have tried making it static but I still don't know how to access it in other classes.

Upvotes: 0

Views: 102

Answers (3)

Brian Agnew
Brian Agnew

Reputation: 272247

Declare it as a member e.g.

public class A {
   public final List<MyObj> list = new ArrayList<MyObj>();
}

and then

A a = new A();
a.list; // there you go

(note that I've declared it as a List, rather than an ArrayList. That's an implementation issue, and I could simply choose to expose it as a Collection. It's also marked as final since I don't want to change it inadvertently. I can revert that decision later if need be).

It is preferable to make it private and access it via an accessor e.g.

public class A {
   private final List<MyObj> list = new ArrayList<MyObj>();

   public List<MyObj> getList() {
      return list;
   }
}

A a = new A();
a.getList();

although someone external to your class could modify it (!). So you could copy it prior to exposing it, or wrap it using Collections.unmodifiableList().

It is better still to hide it completely and ask class A to do something for you (which may involve that list - that's an implementation detail)

public class A {
   private final List<MyObj> list = new ArrayList<MyObj>();

   public void doSomethingForMe() {
      for (MyObj obj : list) {
         // do something...
      }
   }
}

Upvotes: 3

Richie Hughes
Richie Hughes

Reputation: 130

You could return the ArrayList from the class using a get method.

public class A{

//....

public ArrayList<String> getArray(){
return listToReturn;
}

}

therefore you'd only have to call the method and your variable doesnt have to be static:

A a = new A();

a.getArray();

Upvotes: 1

A4L
A4L

Reputation: 17595

Add a public getter for your list in the class containing it. In the class you want to use the list in, create an instance of class containing the list and get the list by calling the getter method.

class A {
    List<String> list = new ArrayList<>();

    public List<String> getList() {
        return list;
    }
}


Class B {
    public vois useClassAList() {
        A a = new A();
        List<String> list = a.getList();
        // do what ever you want with the list
    }
}

Upvotes: 1

Related Questions