Geo
Geo

Reputation: 96837

Is Java "caching" anonymous classes?

Consider the following code:

for(int i = 0;i < 200;i++)
{
  ArrayList<Integer> currentList = new ArrayList<Integer>() {{
    add(i);
  }};
  // do something with currentList
}

I'm just curious :)

Upvotes: 11

Views: 2437

Answers (2)

notnoop
notnoop

Reputation: 59299

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);
}

Upvotes: 16

skaffman
skaffman

Reputation: 403501

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.

Upvotes: 15

Related Questions