46

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

array["a"] = 1;
1
  • 3
    what about multidimensional array like array["a"]["b"]? Commented Jan 16, 2014 at 1:43

4 Answers 4

82

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));
Sign up to request clarification or add additional context in comments.

2 Comments

+1, But couldn't you use Integer.valueOf(1) since a new Integer instance isn't really required? Actually, you could just use the constant 1 instead of needlessly wrapping, right?
@mre the only advantage with not using the constant is that it'll work with versions before 1.5 when autoboxing was introduced. For all modern versions though I agree the constant would be better!
42

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.

Comments

15

No, that would be a Map in Java.

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

Comments

6

No they can't. But they can use chars the ASCII value of the alphabet will be used as the key index

Consider

    String[] a = new String['a' + 1];
    a['a'] = "Hello";
    int[] b = new int['a' + 3];
    b['c'] = 5;

    System.out.println(a[97]);
    System.out.print(b[99]);

This will output

Hello
5

10 Comments

Your arrays is of size 98 to store two values, also 99 (for 'c') is out of range.
The arrays are indeed large for something so simple, however, the question is about whether Java can use a String as an index array key not about how efficient it is. Also, the ascii code for 'a' is 97, add 3 to that and you arrive at 100 for the size of array b. Since the ascii code for 'c' is 99, you can access the value at the 99th index of the array without throwing any IndexOutOfBoundsExceptions. If you have no more reservations, please undo your downvote, so that this answer can be useful to other readers, even if just from a purely educational standpoint
Such operations are actually used in algorithms like R-way Tries where the Radix is the total number of ASCII characters available, so it's not entirely uncommon or inefficient to work with arrays this way
while a workaround is technically a solution, this one is a really, really, really bad suggestion in 9,999 cases out of 10,000. i recommend that you post a serious disclaimer or you will keep on being downvoted. note: i personally did NOT downvote you. but i came THIS close.
Just wanted to point out: the OP wanted to know if arrays can have a String as index, not a character.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.