How to create a simple HashMap using integers?

The following situation: We have a vector with elements and we want to match each element with an integer. The mapping of the elements must be exactly the same as the index of the element inside the vector. Example:

Vector<String> v = new Vector<String>(); v.add("s1"); v.add("s2"); 

The display should be:

 "s1" -> 0 "s2" -> 1 

Approach 1: use v.indexOf("s1") to get an integer. But this approach is slow because you need to look for the right index every time.

Approach 2: Create a HashMap and use put in a for loop to put each element on the map.

Approach 2 is fine, but is there a more suitable solution for creating a Map more directly?

+4
source share
3 answers

If Map intended for such purposes, why does it seem strange to you? I know this simple mapping and using Map can seem really bombastic for a simple task such as getting the index of a given row.

But think about it, approach 1 behaves like a Map<Integer,String> , where you search by value and get its associated key so that you can stick with the opposite Map<String,Integer> , unless you are limited to using Vector .

I am just afraid that this is one of those cases when someone takes the discussion of "performance versus memory" at the nanoscale.

+1
source

An alternative to the HashMap that you might consider is simply using the ArrayList of your rows with Collections.binarySearch to get an integer value. Depending on how many elements you plan to have, this can be done on a par with the HashMap approach.

0
source

but is there a better solution for the card itself?

HashMap will be the most suitable data structure to use.

How to create a simple HashMap using integers?

 HashMap<String, Integer> aHMap = new HashMap<String, Integer>(); aHMap.put("S1", 0); aHMap.get("S1"); 

OR

 HashMap<Integer, String> aHMap = new HashMap<Integer, String>(); aHMap.put(0, "S1"); aHMap.get(0); 
-1
source

All Articles