I have a program which needs to store a couple of simple int values and associate each with a String key. Currently I initialize this member like so:
private Map<String, int[]> imageSizes = new HashMap<String, int[]>();
and then append to it with something like imageSizes.put("some key", new int[]{100, 200});
My question is this - is there a way to give these values a fixed length? I will only ever need 2 elements in each. Java doesn't like the syntax if I try to give the arrays a length in the member definition.
Furthermore, is there any benefit to restricting the array length in this case, or am I just being overzealous in my optimisation?
new int[]
is only legal in a construction where the array elements follow in braces and the compiler can count how many. In the Map, the amount of memory used for the values is just the size of the reference (32 or 64 bits), no matter how large the array is itself. So fixing the size of the array won't change the amount of memory used by the map. In C, you could declare a pointer and then allocate more or less memory to it (or forget to allocate any and crash); Java manages memory for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With