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?
-
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\$user1281750– user12817502015年07月11日 13:09:53 +00:00Commented Jul 11, 2015 at 13:09
-
\$\begingroup\$ @user1281750 you might add this as an answer. \$\endgroup\$GiantTree– GiantTree2015年07月11日 22:27:10 +00:00Commented Jul 11, 2015 at 22:27
1 Answer 1
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 String
s, and one of the Integer
s.
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]);
}
-
\$\begingroup\$
ArrayMap
is a more memory efficientHashMap
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\$GiantTree– GiantTree2015年07月11日 22:26:37 +00:00Commented 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\$SirPython– SirPython2015年07月11日 22:35:30 +00:00Commented Jul 11, 2015 at 22:35