1

I need to access an ArrayList through multiple functions in my main Java class file (the class file that contains main()).

To save myself having to pass the array list between functions, can I declare it outside of the methods? Is this bad practise? I understand this is okay with class files that are initialised as objects (private instance variables for example) - but what about the Main class file?

EDIT: It will be the only class variable declared and available to all functions in that class.

7ahid
  • 420
  • 1
  • 5
  • 12
  • It depends on what you do with arraylist. What do you stored in this arraylist ? – hkaraoglu Apr 30 '16 at 16:06
  • It can be bad, and often is, but not always. It largely depends on how it's implemented, and what other techniques exist. If there's no other way to do this, it's probably OK. – markspace Apr 30 '16 at 16:16

2 Answers2

2

If you declare it as private it's okay. What it would be a very bad practice is to declare it as public.

jpuriol
  • 362
  • 2
  • 14
1

You are good as long as you keep it private, since that way you'll make sure it is accessible only from within that class. On the other hand, if you do require it to be accessed from other classes, use getter setter methods while still keeping it private within the class itself.

Community
  • 1
  • 1
Sajib Acharya
  • 1,666
  • 5
  • 29
  • 54