Java associative-array

dobs picture dobs · Feb 25, 2011 · Viewed 266k times · Source

How can I create and fetch associative arrays in Java like I can in PHP?

For example:

$arr[0]['name'] = 'demo';
$arr[0]['fname'] = 'fdemo';
$arr[1]['name'] = 'test';
$arr[1]['fname'] = 'fname';

Answer

Johan Sjöberg picture Johan Sjöberg · Feb 25, 2011

Java doesn't support associative arrays, however this could easily be achieved using a Map. E.g.,

Map<String, String> map = new HashMap<String, String>();
map.put("name", "demo");
map.put("fname", "fdemo");
// etc

map.get("name"); // returns "demo"

Even more accurate to your example (since you can replace String with any object that meet your needs) would be to declare:

List<Map<String, String>> data = new ArrayList<>();
data.add(0, map);
data.get(0).get("name"); 

See the official documentation for more information