Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing List in constructor or field declaration

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.

like image 681
Jankosha Avatar asked Nov 19 '15 23:11

Jankosha


People also ask

Should my constructors use initialization lists or assignment?

Initialization lists. In fact, constructors should initialize as a rule all member objects in the initialization list.

What is constructor initialization list?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.

Is constructor used for initialization?

A class object with a constructor must be explicitly initialized or have a default constructor. Except for aggregate initialization, explicit initialization using a constructor is the only way to initialize non-static constant and reference class members.


1 Answers

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.

like image 147
Bohemian Avatar answered Nov 16 '22 01:11

Bohemian