3 回答
TA贡献2016条经验 获得超9个赞
2009/05/27 16:35 1,602 DemoApp2$1.class2009/05/27 16:35 1,976 DemoApp2$10.class2009/05/27 16:35 1,919 DemoApp2$11.class2009/05/27 16:35 2,404 DemoApp2$12.class2009/05/27 16:35 1,197 DemoApp2$13.class/* snip */2009/05/27 16:35 1,953 DemoApp2$30.class2009/05/27 16:35 1,910 DemoApp2$31.class2009/05/27 16:35 2,007 DemoApp2$32.class2009/05/27 16:35 926 DemoApp2$33$1$1.class2009/05/27 16:35 4,104 DemoApp2$33$1.class2009/05/27 16:35 2,849 DemoApp2$33.class2009/05/27 16:35 926 DemoApp2$34$1$1.class2009/05/27 16:35 4,234 DemoApp2$34$1.class2009/05/27 16:35 2,849 DemoApp2$34.class/* snip */2009/05/27 16:35 614 DemoApp2$40.class2009/05/27 16:35 2,344 DemoApp2$5.class2009/05/27 16:35 1,551 DemoApp2$6.class2009/05/27 16:35 1,604 DemoApp2$7.class2009/05/27 16:35 1,809 DemoApp2$8.class2009/05/27 16:35 2,022 DemoApp2$9.class
class
class
List<String> list = new ArrayList<String>() {{ add("Hello"); add("World!");}};
List<String> list = new ArrayList<String>() { // Instance initialization block { add("Hello"); add("World!"); }};
List<Integer> intList = [1, 2, 3, 4];Set<String> strSet = {"Apple", "Banana", "Cactus"};Map<String, Integer> truthMap = { "answer" : 42 };
实验
ArrayList
"Hello"
"World!"
add
方法1:双支座初始化
List<String> l = new ArrayList<String>() {{ add("Hello"); add("World!");}};
ArrayList
add
List<String> l = new ArrayList<String>();l.add("Hello");l.add("World!");
试验1:
class Test1 { public static void main(String[] s) { long st = System.currentTimeMillis(); List<String> l0 = new ArrayList<String>() {{ add("Hello"); add("World!"); }}; List<String> l1 = new ArrayList<String>() {{ add("Hello"); add("World!"); }}; /* snip */ List<String> l999 = new ArrayList<String>() {{ add("Hello"); add("World!"); }}; System.out.println(System.currentTimeMillis() - st); }}
试验2:
class Test2 { public static void main(String[] s) { long st = System.currentTimeMillis(); List<String> l0 = new ArrayList<String>(); l0.add("Hello"); l0.add("World!"); List<String> l1 = new ArrayList<String>(); l1.add("Hello"); l1.add("World!"); /* snip */ List<String> l999 = new ArrayList<String>(); l999.add("Hello"); l999.add("World!"); System.out.println(System.currentTimeMillis() - st); }}
ArrayList
ArrayList
System.currentTimeMillis
Test1 Times (ms) Test2 Times (ms)---------------- ---------------- 187 0 203 0 203 0 188 0 188 0 187 0 203 0 188 0 188 0 203 0
ArrayList
.class
Test1
TA贡献1780条经验 获得超3个赞
this$0
第二个问题:新的HashSet必须是实例初始化器中使用的“this”。有人能说明这个机制吗?我天真地期望“this”指的是初始化“口味”的对象。
this
public class Test { public void add(Object o) { } public Set<String> makeSet() { return new HashSet<String>() { { add("hello"); // HashSet Test.this.add("hello"); // outer instance } }; }}
HashSet.add()
public Set<String> makeSet() { return new HashSet<String>() { { add("hello"); // not HashSet anymore ... } @Override boolean add(String s){ } }; }
添加回答
举报