1
\$\begingroup\$

I'm currently working on an Android app and I need to translate keys of type String to Integers which are determined at compile time of R.raw.
Right now I have found two ways of creating such a Map that holds all (needed) values of R.raw:

private static final Map<String, Integer> map = ImmutableMap.<String, Integer>builder()
 .put("...", R.raw.id)
 ... 
 .build();

and

private static final Map<String, Integer> map = new ArrayMap<>();
static {
 map.put("...", R.raw.id);
 ...
}

My questions are:

  • Are there better ways of creating a Map to lookup keys and return values that are determined at compile time? I don't want to use reflection.
    and
  • Which one of those ways would you prefer?
asked Jul 1, 2015 at 19:33
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Because you are mentioning raw, I would suggest placing your files in assets folder, you can reference them by filename from the AssetManager. Then you can just use a List of Strings and you don't need to create a Map. \$\endgroup\$ Commented Jul 11, 2015 at 13:09
  • \$\begingroup\$ @user1281750 you might add this as an answer. \$\endgroup\$ Commented Jul 11, 2015 at 22:27

1 Answer 1

2
\$\begingroup\$

There is not such thing as ArrayMap in standard Java. Therefore, I am just going to assume that you meant HashMap.


I would choose neither of those options. Depending on how many elements you need to insert into that Map, you could end up with a big chunk of code that is just a group of add calls.

I recommend creating two arrays: one of the Strings, and one of the Integers.

Then, all you have to do is create a loop that inserts all the values into the map.

Here is what I came up with:

String[] foos = {...};
Integer[] bars = {...};
Map<String, Integer> map = new HashMap<String, Integer>();
for(int i = 0, length = foo.length; i < length; i++) {
 map.put(foos[i], bars[i]);
}
answered Jul 11, 2015 at 22:09
\$\endgroup\$
2
  • \$\begingroup\$ ArrayMap is a more memory efficient HashMap designed for Android. I'm currently checking user1281750's approach, but your's might come in handy, when you can't move resources to assets (in Android). \$\endgroup\$ Commented Jul 11, 2015 at 22:26
  • \$\begingroup\$ @GiantTree Ah, I see. I was wondering where ArrayMap was coming from (I am not experienced with Android). \$\endgroup\$ Commented Jul 11, 2015 at 22:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.