Can Java use String as an index array key? (ex: array["a"]=1;)

Can Java use a String as an index array key? Example:

array["a"] = 1;

Solution 1:

No.

To do something like this, you have to use a Map.

Map<String, Integer> aMap = new HashMap<String, Integer>();
aMap.put("a" , Integer.valueOf(1));

Solution 2:

No - you want a map to do that:

Map<String, Integer> map = new HashMap<>();
map.put("a", 2);

Then to get it:

int val = map.get("a"); //2

You can only use the square bracket syntax for arrays, not for any of the collections. So something like:

int val = map["a"]; //Compile error

Will always be illegal. You have to use the get() method.

Solution 3:

No, that would be a Map in Java.

(The type would be Map<String,Integer>.)