0

I'm creating an app and I need to store ~250 different sizes and positions of objects for 5 different screen aspect ratios.

The app detects the ratio on startup and detects the ratio so I can later access object's pos/size like:

someXYZObject.setPosition(Constants.getPosition(SOME_XYZ_OBJECT));

So I need to do a pattern like some Enums in Constants class, for ex:

class Constants{

// some construction

    public enum RATIO_16_9{
        ELEMENT1(3f,2f,1f,6f),
        ELEMENT2(6f,3f,3f,1f),
        ELEMENT3(7f,3f,3f,3f);
        //getters, setters, constructor
    }

    public enum RATIO_5_3{
        ELEMENT1(10f,10f,5f,5f),
        ELEMENT2(23f,2f,2f,2f),
        ELEMENT3(7f,6f,3f,3f);
        //getters, setters, constructor
    }

    // this enum is only for the getter below, to get the right ratio and it's value
    public enum Element{
        ELEMENT1, ELEMENT2, ELEMENT3;
    }
    //etc

    public static Size getElementsSize(Element val){
        //some returns, switches, loops
    }

}

This looks crazy but I thought about it and there's no 'clear way' to write this. I need to write 1250 values in code and that's it.

The question is:

Does enum values like ELEMENT1(3f,2f,1f,6f) initialize on application startup (cause enums are static) and allocate memory or only if I call values() method/make an object of enum type?

I know that this is kinda stupid question, but you know, I'm just lost.

  • TL;DR for the link: They initialize at class load time which, in your case, is basically the first time you either call one of the enum's static methods or use one of their values. All *you* need to know is they're ready for you when you need them. Here's an example: http://ideone.com/zPdZZk - Look at the output timestamps, you can see when the enum classes are loaded. You could force it by doing e.g. `Class.forName("Main$Example1");` early on in that example; there's usually no reason for this but just as a demonstration. – Jason C Sep 11 '16 at 20:18
  • Oh, thanks Jason. I couldn't name it so I didn't find ;( One more question to you! If I make a method and initialize a field in it, it won't allocate any memory if I won't call the method, is it right? –  Sep 11 '16 at 20:21
  • Of course the code in methods doesn't run until you call them. So if you do `new Widget()` in a method it does nothing if you never call the method. Is that what you mean? – Jason C Sep 11 '16 at 20:22

0 Answers0