Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java support associative arrays? [duplicate]

Tags:

java

arrays

I'm wondering if arrays in Java could do something like this:

int[] a = new int[10];
a["index0"] = 100;
a["index1"] = 100;

I know I've seen similar features in other languages, but I'm not really familiar with any specifics... Just that there are ways to associate values with string constants rather than mere numeric indexes. Is there a way to achieve such a thing in Java?

like image 884
Fugogugo Avatar asked Feb 14 '11 14:02

Fugogugo


1 Answers

You can't do this with a Java array. It sounds like you want to use a java.util.Map.

Map<String, Integer> a = new HashMap<String, Integer>();

// put values into the map
a.put("index0", 100); // autoboxed from int -> Integer
a.put("index1", Integer.valueOf(200));

// retrieve values from the map
int index0 = a.get("index0"); // 100
int index1 = a.get("index1"); // 200
like image 145
Matt Ball Avatar answered Sep 20 '22 17:09

Matt Ball