Is it possible to create a HashMap whose key is an array of integers?
I´m accustomed to use Python and just recently I began working with Java. In my job I need to create a HashMap with keys like:
map.put([5,2], 1);
map.put([3,2], 0);
and so on. I´m using it to later on test if a pair of those numbers are present in the map, if yes, then do something, if not, continue.
To do so I tried the following:
Map<Array, Boolean> test = new HashMap<Array, Boolean>();
int[] a1 = {5,2};
test.put(a1, true);
Eclipse gives the message (“The arguments are not applicable to int[]…”). But any configuration I´ve done I get some error.
I tried using ArrayList, Objects inside the map, nested HashMap and so on but none worked (in python it´s very easy, I´d just write dict[(5,2)] = 1, so I imagine in Java there´s something simple like that). I was suggested to transform the numbers into Strings and add a colon between then, like:
map.put("5:2", 1);
and later on I break the string again but if this is the solution I´ll go back to Python ;)!!
Probably this is a very simple question but I couldn´t find the answer, hope you can help me.
Thanks in advance!
If you want to check for the existance of your entry, you can use a
Set(a useful concrete implementation isHashSet.You can use an
Listas I have done above – but that doesn’t guarantee that all your lists are exactly two elements long (if that is indeed a constraint). To make it a bit more robust, you could create your own class to represent the tuple. If you do, make sure you implementequals()andhashCode()(here’s an article explaining good practice).Arrays.asList()is a useful way of creating a list in-line in the code. A more general list is anArrayList.