Sampoo
Sampoo

Reputation: 13

What is the difference between these two ways of creating a TreeMap (or any map)?

I'm reading some code in a project and came across this line of code:

private Map<String, Map<String, List<String>>> wordbatch;

Further on in the code, I reached another line of code in the constructor:

wordbatch = new TreeMap<String, Map<String, List<String>>>;

Would this single line of code have the same effect?:

Map<String, Map<String, List<String>>> wordbatch = new TreeMap<String, Map<String, List<String>>>();

What are the differences in this line of code and the two lines of code above?

Any help is appreciated, and thank you so much. Trying to enhance my knowledge about maps.

Upvotes: 0

Views: 52

Answers (1)

RealSkeptic
RealSkeptic

Reputation: 34628

There are a few subtle differences between the statements you presented.

In the first case, you are declaring an instance variable (whose value is null) on line X, and somewhere in the code on line Y, you give it another value, a new map.

In the second case, you are both declaring and giving it a value. However, it's important where this is happening.

  • If you put that full declaration where the original declaration was, on line X, then it's still an instance variable. However,
    1. You forgot your private. This may be important if you don't want other classes in the same package to use that variable directly.
    2. If there is any part of the code that relies on the fact that this variable may be null in the beginning (look for code that checks if this variable is null), then you may be introducing a bug by initializing it in the declaration.
  • If you put that declaration where the original assignment was, on line Y, then you are no longer declaring an instance variable. This becomes a local variable. The rest of the code, which expects this instance variable to exist, will produce compilation errors. An instance variable must be declared outside of any method or constructor.

Note that if line Y is in your constructor, and it's the only constructor, then there is very little difference in the two ways of initializing.

Upvotes: 2

Related Questions