0 votes
1 view
in Java by (3.5k points)

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';

1 Answer

0 votes
by (46.1k points)

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 correct to your insstannce (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

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 14 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...