11

Consider the following code:

for(int i = 0;i < 200;i++)
{
  ArrayList<Integer> currentList = new ArrayList<Integer>() {{
    add(i);
  }};
  // do something with currentList
}
  • How will Java treat the class of currentList?
  • Will it consider it a different class for each of the 200 objects?
  • Will it be a performance hit even after the first object is created?
  • Is it caching it somehow?

I'm just curious :)

Basit Anwer
  • 6,742
  • 7
  • 45
  • 88
Geo
  • 93,257
  • 117
  • 344
  • 520
  • 3
    Afaik an anonymous class is a simple class with just a generated name. nothing more. Caching is performed as with every class in the classloader. – ZeissS Jan 12 '10 at 17:10
  • actually this will generate a compiler error: `i` is not final, which would be bad idea for as loop counter. But a good question! – user85421 Jan 12 '10 at 19:10

2 Answers2

16

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);
}
notnoop
  • 58,763
  • 21
  • 123
  • 144
15
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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 2
    ... and the referece "currentList" will be not reachable after the for loop and created again. In that sense the object to which it makes reference ( the inner class instance ) will be marked for garbage collection immediately. – OscarRyz Jan 12 '10 at 17:25