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[100]would allocate memory for 100 values, whereasnew int[]would allocate some amount declared to be 'sufficient' by the compiler and resized when it runs out. Not so in Java? All of this only applies to primitive types, of course...new int[]is only legal in a construction where the array elements follow in braces and the compiler can count how many. My point is that in the Map, the amount of memory used for the values is just the size of the reference, 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 doesn't work like that.