I have a class MyMap which extends java.util.HashMap, the following code works as a block of statements but I don't understand the use of the extra curly braces
MyMap m = new MyMap() {
{
put("some key", "some value");
}
};
Now why do I need the extra curly braces, can't I just do this (but this raises compile error)
MyMap m = new MyMap() {
put("some key", "some value");
};
A block in Java is a set of code enclosed within curly braces { } within any class, method, or constructor. It begins with an opening brace ( { ) and ends with an closing braces ( } ). Between the opening and closing braces, we can write codes which may be a group of one or more statements.
Blocking methods in java are the particular set of methods that block the thread until its operation is complete. So, they will have to block the current thread until the condition that fulfills their task is satisfied. Since, in nature, these methods are blocking so-called blocking methods.
Java supports three different types of statements: Expression statements change values of variables, call methods, and create objects. Declaration statements declare variables. Control-flow statements determine the order that statements are executed.
A block is a type of statement that contains declarations and other statements surrounded by braces { int i = 1; System. out. println(i); } . Some statements are built using other statements.
This:
MyMap m = new MyMap() {
....
};
creates an anonymous inner class, which is a subclass of HashMap
.
This:
{
put("some key", "some value");
}
is an instance initializer. The code is executed when the instance of the anonymous subclass is created.
What you're actually doing here is define an anynomous subclass of MyMap, which was probably not your intent... The outermost curly braces are around the class contents. And in Java, you cannot put instructions directly inside a class block: if you need code to be executed when the class is instantiated, you put it into a constructor. That's what the innermost braces are for: they delimit an initializer for your anonymous class.
Now, you probably wanted something like:
MyMap m = new MyMap();
m.put("some key", "some value");
Just create an instance of MyMap
and call put
on it, no anonymous class involved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With