What's the best practice for initializing an ArrayList field in Java (to avoid testing null value) ?
At declaration, like this :
private List<String> myList = new ArrayList<String>();
Or in the getter, like this :
public List<String> getMyList() {
if(myList == null) {
myList = new ArrayList<String>();
}
return myList;
}
Or, in the constructor :
public Test(){
myList = new ArrayList<String>();
}
Maybe it's the same, but I am curious to know.
The first option allows you to do a
private final List<String> myList = new ArrayList<>();
Thus preventing you from accidentally creating a completely new list later on; thus helping with (many, not all) multi-threading issues. In addition to that, now the compiler can help you to make sure that your field is initialized exactly once.
Beyond that, the second option can be seen as "lazy initialization". And in that sense: it can be seen as "optimization choice"! And from there: many people advocate on avoiding premature optimization!
You know, when you can't rely on the list being already created that can cause a lot of trouble. So even when coming from that perspective, you have another argument to prefer option 1!
Edit, regarding the compiler option: from a semantics point there option 1 and 3 are (more or less) "equal" [hint: if you find that it makes a difference in your code if you choose option1 or option3 ... that would be a good indication that your are doing something terribly wrong in your code).
Nonetheless, the one thing that can make a difference - if you have a "dependency injection" constructor, like:
public YourClass() { this(new ArrayList<String>); }
YourClass(List<String> incomingList) { myList = incomingList; }
This solution makes sense for those kinds of objects that you need to "control"; in the sense of: you require to pass mocks to your class to enable unit testing.
Long story short:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With