Question

How can I declare an instance variable like this:

private ArrayList<Contact> list = new ArrayList<Contact>();

or can I only write private ArrayList<Contact> list; and then create new ArrayList objects every time in every method?

Was it helpful?

Solution

You can do both. The first is called an initialization, and the second is just a declaration.

Related SO Topic - Java: define terms initialization, declaration and assignment

OTHER TIPS

You can also initialize your variable in the class constructor:

this.list = new ArrayList<Contact>();

It's certainly fine to declare it like this:

private ArrayList<Contact> list;  // initializes list to null

and then create a new ArrayList:

list = new ArrayList<Contact>();  // assignment statement

But you probably wouldn't want to do this assignment "every time in every method". Each time you do the above assignment statement, the program creates an empty array and sets list to that; and if list were previously another ArrayList, everything in that list would be thrown away (unless you had copied it somewhere else). This probably isn't what you want. Most likely, you want to create the new array just once, so the assignment statement would probably be put in the constructor(s), as in @coder's answer. If you do have a method where you actually do want to create a new empty ArrayList and get rid of the previous data, you can do so with the above assignment (or just say list.clear() which removes all elements from an ArrayList).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top