Is Java “caching” anonymous classes?

百般思念 提交于 2019-12-01 15:41:52
ArrayList<Integer> currentList = new ArrayList<Integer>() {{
    add(i);
  }};

is creating a new instance of the anonymous class each time through your loop, it's not redefining or reloading the class every time. The class is defined once (at compile time), and loaded once (at runtime).

There is no significant performance hit from using anonymous classes.

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<Integer> {
    OuterClass$1(int i) {
      super();
      add(i);
    }
}

for (int i = 0; i < 200; i++) {
    ArrayList<Integer> currentList = new OuterClass$1(i);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!