Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for initializing an ArrayList field in Java [closed]

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.

like image 443
JavaDev Avatar asked Jun 30 '16 13:06

JavaDev


1 Answers

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:

  • Prefer option1, if possible: using final
  • Use option3 if dependency injection is required
  • Avoid option2 unless you have really good reasons to go for it
like image 180
GhostCat Avatar answered Sep 28 '22 23:09

GhostCat