Is Java “caching” anonymous classes?

前端 未结 2 2009
南方客
南方客 2021-01-17 17:45

Consider the following code:

for(int i = 0;i < 200;i++)
{
  ArrayList currentList = new ArrayList() {{
    add(i);
  }};
  /         


        
2条回答
  •  攒了一身酷
    2021-01-17 18:24

    The compiler is going to transform any anonymous class to a named inner class. So your code, will be transformed to something along the lines of:

    class OuterClass$1 extends ArrayList {
        OuterClass$1(int i) {
          super();
          add(i);
        }
    }
    
    for (int i = 0; i < 200; i++) {
        ArrayList currentList = new OuterClass$1(i);
    }
    

提交回复
热议问题