Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
  • 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 :)

like image 290
Geo Avatar asked Jan 12 '10 17:01

Geo


People also ask

What are anonymous classes in Java?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

Does Java have anonymous types?

In Java, a class can contain another class known as nested class. It's possible to create a nested class without giving any name. A nested class that doesn't have any name is known as an anonymous class. Anonymous classes usually extend subclasses or implement interfaces.

Can Anonymous classes be private?

3.12. An anonymous class cannot define any static fields, methods, or classes, except for staticfinal constants. Interfaces cannot be defined anonymously, since there is no way to implement an interface without a name. Also, like local classes, anonymous classes cannot be public, private, protected, or static.

Which are two ways to create Java anonymous?

Java Anonymous inner class can be created in two ways: Class (may be abstract or concrete). Interface.


1 Answers

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.

like image 142
skaffman Avatar answered Sep 27 '22 17:09

skaffman