-2

Is there a way to use names as indexes in arrays? like

ary["name"]="ABCD";
ary["age"]="20";

System.out.println(ary["name"] + " " + ary["age"]);

3 Answers3

3

Use a Map instead.

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

In your case, your snippet would be:

Map<String,String> ary = new HashMap<String,String>();
ary.put("name","ABCD");
ary.put("age", "20");

System.out.println(ary.get("name") + " " + ary.get("age"));
Pier-Alexandre Bouchard
  • 5,135
  • 5
  • 37
  • 72
2

Maybe you can use a HashMap

Example:

HashMap<String,String> map = new HashMap<String,String>();
map.put("hello","hi");
System.out.println(map.get("hello"));

output: hi

Sarthak Mittal
  • 5,794
  • 2
  • 24
  • 44
2

It'd be a dictionary at that point. From: How do you create a dictionary in Java?:

Map<String, String> map = new HashMap<String, String>();
map.put("dog", "type of animal");
System.out.println(map.get("dog"));
Community
  • 1
  • 1
Jackson
  • 559
  • 7
  • 20