Reputation: 8113
class Node {
char val;
boolean wordEnd;
Map<Character, Node> map = new HashMap<>();
public Node() {}
public Node(char v) {
val = v;
}
}
In Java, when is map = new HashMap<>()
being called?
I see I have 2 constructors here. But when is the "map" line being called? Before or after the constructor?
Also, why can we define map
with new
like this? In C++, I think it is not right.
I thought we should declare the map
first, then in constructor, we new
it.
Upvotes: 1
Views: 58
Reputation: 726809
when is
map = new HashMap<>()
being called?
All initializers are called in the order that they appear in the text of the class. All initializers complete before the constructor's code gets started, so you shouldn't be afraid that your map
is still null
when you are inside the constructor. See section 12.5 of JLS for details.
Also, why can we define map with new like this? In C++, I think it is not right.
C++ lacks this syntax, except for static initializers in the later versions of the standard. Even though Java and C++ borrow from common sources, they remain very different languages, with rather different philosophies behind them.
Upvotes: 3