Reputation: 13
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
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.
private
. This may be important if you don't want other classes in the same package to use that variable directly.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