This seems like a pretty basic question, but I'm still learning Java and all the nuances of OOP.

I have several classes in my program and they all need access to the same ArrayList (the one with all the data in it.) What's the best way to share that list? Do I pass it to each method that needs it (it's passed by reference, right?) or do I make it a public global so that all methods in all my classes have access?

Thanks everyone, I really appreciate the help...

-Bill

Yeah, ArrayLists are passed by reference. It's better to pass it than having global values lying around.

You could pass the (reference to the) ArrayList to the constructors of the various dependent classes so they all have access to it when their instances are created.

Giving them direct access to the list (via passing refs or sharing a global) can be dangerous - anyone can make any change to the list at any time, regardless of any side effects that it may have in other classes. If that's a problem you should wrap the list in a class and provide public methods for everyone else to use. That way you central control over changes etc.

Yeah, ArrayLists are passed by reference. It's better to pass it than having global values lying around.

Ah, but since they are passed by reference, that seems just as bad as making them global since there is only one copy.

Giving them direct access to the list (via passing refs or sharing a global) can be dangerous - anyone can make any change to the list at any time, regardless of any side effects that it may have in other classes. If that's a problem you should wrap the list in a class and provide public methods for everyone else to use. That way you central control over changes etc.

Okay, just as I suspected. Thanks!

-Bill

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.