简体   繁体   English

ENUM存储(内存等)

[英]ENUM storage (memory, etc)

I was just asking myself a little question, and I'm not sure if I can find the right answer to this: 我只是问自己一个小问题,我不确定我是否能找到正确答案:

If I use an ENUM in Java, with an own constructor (and many, many, maaaaany parameters) - are those stored in Memory every time the program gets executed, or are they only 'loaded' in Memory, if they get used? 如果我在Java中使用ENUM,使用自己的构造函数(以及许多,许多,maaaaany参数) - 每次程序执行时存储在内存中的那些,或者它们是否仅在内存中“加载”,如果它们被使用?

What I mean is, if I have an ENUM with 400 entries, and only use one of the entries - are all others still present in Memory? 我的意思是,如果我有一个包含400个条目的ENUM,并且只使用其中一个条目 - 所有其他条目仍然存在于内存中吗?

some pseudocode: 一些伪代码:

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 only use ENTRY_A, and dont touch ENTRY_B, ENTRY_C, etc - how will Java handle that exactly? 如果我只使用ENTRY_A,并且不要触及ENTRY_B,ENTRY_C等 - 那么Java将如何处理?

Thanks for the Answer - and yes, this is mainly curiousity 谢谢你的回答 - 是的,这主要是好奇心

Yes everything will be loaded to memory even though you use only one ENUM constant. 是的,即使您只使用一个ENUM常量,所有内容都将加载到内存中。

Enum is special type of class and all fields are constants, so when you load the ENUM, then itself it loads everything to memory. 枚举是特殊类型的类,所有字段都是常量,因此当您加载ENUM时,它本身会将所有内容加载到内存中。

第一次使用枚举时,将触发类初始化,所有值都将被创建并存储在内存中,就像任何其他类一样。

You could always try it by yourself. 你总是可以自己尝试一下。 Just put for example System.println("test") in the constructor of your enum and empirically embrace the results. 只需将例如System.println("test")放在enum的构造函数中,然后根据经验包含结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM