Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Java Map of fixed-length array values?

Tags:

java

arrays

map

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?

like image 932
pospi Avatar asked Jan 18 '23 16:01

pospi


1 Answers

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.

like image 159
Andrew Lazarus Avatar answered Jan 27 '23 20:01

Andrew Lazarus