How to create a Java map of fixed-length values?

I have a program that needs to store a couple of simple int values ​​and bind them to a string key. I am currently initializing this element as follows:

private Map<String, int[]> imageSizes = new HashMap<String, int[]>(); 

and then add to it something like imageSizes.put("some key", new int[]{100, 200});

My question is, is there a way to give these values ​​a fixed length? I will need only 2 elements in each. Java doesn't like the syntax if I try to give arrays a length in a member definition.

Also, is there any use for limiting the length of the array in this case, or am I just overrated in my optimization?

+4
source share
4 answers

new int[] is only legal in a construct in which array elements follow in braces, and the compiler can calculate how many. On a Map, the amount of memory used for values ​​is simply the size of the link (32 or 64 bits), regardless of how large the array itself is. Therefore, fixing the size of the array will not change the amount of memory used by the card. In C, you can declare a pointer and then allocate more or less memory for it (or forget to allocate and crash); Java manages memory for you.

+2
source

You can wrap it in a simple, reusable and self-documenting class:

 public class Size { private int width; private int height; public Size(int width, int height) { this.width = width; this.height = height; } public int getWidth() { return width; } public int getHeight() { return height; } // Add setters if necessary. } 

And use it as follows:

 Map<String, Size> sizes = new HashMap<String, Size>(); sizes.put("some key", new Size(100, 200)); // ... 
+2
source

You can use a class that extends HashMap and provides this special functionality:

 public class ImageHashMap extends HashMap<String, int[]> { public void putArray(String key, int a, int b) { put(key, new int[]{a, b}); } } 

To call:

 ImageHashMap im = new ImageHashMap(); im.putArray("some key", 100, 200); 
+2
source

In addition to the bohemian solution, you can protect the original put method from HashMap as follows:

 @Override public int[] put(String key, int[] value) { throw new UnsupportedOperationException("Sorry, operation not allowed."); } 
0
source

All Articles