I need to make an int array using Strings instead of ints. EX: int["number2"] = 0; instead of int[2] = 0;

Does anyone know how to do this?

Thanks for your time.

share|improve this question

68% accept rate
feedback

4 Answers

up vote 2 down vote accepted

Java doesn't support associative arrays, but you could use a HashMap:

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("key1", 25);
map.put("key2", 4589); 

map.get("key1") will return 25.

share|improve this answer
feedback

You are not looking for an array but for an associative array.

In Java, in practice, every class that implements Map can be used as an associative container, since they can map keys to values (TreeMap<K,V>, HashMap<K,V>, and so on)

share|improve this answer
feedback

This syntax looks very like a map in Groovy, In Java, you could use something like a Map<String, Integer>.

share|improve this answer
feedback

you could use a HashMap - see here for more info!

share|improve this answer
2  
Or more generally, any kind of Map. – cheeken Sep 1 at 23:26
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.