22

I was wondering whether there is a difference in initializing objects like ArrayList<> and stuff in field declaration or constructor.

Is there a difference in memory usage, performance or anything like that or is it completely the same?

Option 1:

class MyClass {
     private List<String> strings = new ArrayList<String>();
}

Option 2:

class MyClass {
    private List<String> strings;
    public MyClass() {
        strings = new ArrayList<String>();
    }
}

It may be a stupid question, or a very basic one, but I like to build from the start, I like to understand all that I see.

Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30
Jankosha
  • 221
  • 1
  • 2
  • 3

4 Answers4

11

There is a difference: when initialization occurs. Fields are initialized first, then the constructor fires.

In your trivial example, there would be no practical difference, but if another field depended on the List field for initialization, the constructor version would explode with a NPE.

Consider:

 private List<String> strings = Arrays.asList("foo", "bar");
 private String stringsDescription = strings.toString();

If you moved initialization of strings to the constructor, the initialization of stringsDescription would explode with a NPE.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
5

take a look at this Default constructor vs. inline field initialization

There's also other ways to initialize values: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

IMHO, initializing in default constructor is a little bit more risky unless you are sure that is the only constructor you have. If you have more than one, you need to call always default (good practice) or duplicate your initialization code.

Community
  • 1
  • 1
Gervasio Amy
  • 285
  • 2
  • 8
4

It's essentially the same thing. Doing it in the constructor gives more control over it (for example different constructors can do different things) but the final result is identical.

You will see no performance difference in memory, CPU, or anything else doing it either way.

Tim B
  • 40,716
  • 16
  • 83
  • 128
1

Another difference arises when you declare the arrayList as a static variable so that it can be accessed from other classes without instantiating the class the holds it. In that setting, you need to initialize upon declaration and not in the constructor. Consider the following example that gives you a NullPointerException:

import java.util.ArrayList;

public class Dogs {
    public static ArrayList<Dog> dogList;

    public Dogs(){
        dogList = new ArrayList<>();
    }
}

class Dog {
    String breed;

    public Dog(String breed){
        this.breed = breed;
    }

    public static void main(String[] args) {
        Dog dog1 = new Dog("pug");
        Dogs.dogList.add(dog1);
    }
}
pakpe
  • 5,391
  • 2
  • 8
  • 23