ENUM storage (memory, etc.)

I just asked myself a little question, and I'm not sure if I can find the right answer to this question:

If I use ENUM in Java, with my own constructor (and many, many maaaaany parameters), are those stored in memory every time the program is executed, or are they only β€œloaded” into memory if they are used?

What do I mean if I have an ENUM with 400 entries and only one of the entries is used - are they still present in memory?

some pseudo code:

public enum Type { ENTRY_A(val1, val2, val3, val4, new Object(val5, val6, val7, ...)), ENTRY_B(val1, val2, val3, val4, new Object(val5, val6, val7, ...)), ENTRY_C(val1, val2, val3, val4, new Object(val5, val6, val7, ...)), ... } 

If I use only ENTRY_A and do not touch ENTRY_B, ENTRY_C, etc. - how will Java handle just that?

Thanks for the answer - and yes, it's basically curiosity

+4
source share
3 answers

Yes, everything will be loaded into memory, although you use only one ENUM constant.

Enum is a special type of class, and all fields are constants, so when loading ENUM, it loads everything into memory.

+4
source

The first time you use an enumeration, this will cause the class to be initialized, and all values ​​will be created and stored in memory the same way as with any other class.

+4
source

You can always try it on your own. Just put, for example, System.println("test") in the constructor of your enum and empirically circle the results.

+1
source

Source: https://habr.com/ru/post/1441833/


All Articles