1, so the code at compile-time error
public class Test2 {
public static void main(String[] args) {
int i;
for(int i=0; i<10; i++) {
System.err.println(i);
}
}
}
会提示“Duplicate local variable i”
2, so the code is not
public class TestInnerClass {
public static void main(String... strs) throws Exception {
int i;
class Local {
{
for(int i=0;i<10;i++) {
System.err.println(i);
}
}
}
new Local();
}
}
Curly brackets initialization of Java: using anonymous inner classes to perform an initialization operation.
Efficiency and the resulting .class
file structure
Using two braces standard initialization may not be set from the collection efficiency for the initialization step. The reason is initialized with curly brackets will lead to internal documents of the class, and this process will affect the efficiency of the code.
For example the following code:
// Double brace initialization
class Test1 {
public static void main(String[] args) {
long st = System.currentTimeMillis();
Set<Integer> set0 = new HashSet<Integer>() {{
add(1);
add(2);
}};
Set<Integer> set1 = new HashSet<Integer>() {{
add(1);
add(2);
}};
/* snip */
Set<Integer> set999 = new HashSet<Integer>() {{
add(1);
add(2);
}};
System.out.println(System.currentTimeMillis() - st);
}
}
// Normal initialization
class Test2 {
public static void main(String[] s) {
long st = System.currentTimeMillis();
Set<Integer> set0 = new HashSet<Integer>();
set0.add(1);
set0.add(2);
Set<Integer> set1 = new HashSet<Integer>();
set1.add(1);
set1.add(2);
/* snip */
Set<Integer> set999 = new HashSet<Integer>();
set999.add(1);
set999.add(2);
System.out.println(System.currentTimeMillis() - st);
}
}
A javac
command is generated first code compile 1000 .class
file as follows:
Test1$1.class
Test1$2.class
...
Test1$1000.class
While the output from the run-time program of view, curly brackets initialization significantly slower than the normal initialization code. Difference of around 100ms.