Java associative-array Java associative-array java java

Java associative-array


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");// etcmap.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


Java doesn't have associative arrays like PHP does.

There are various solutions for what you are doing, such as using a Map, but it depends on how you want to look up the information. You can easily write a class that holds all your information and store instances of them in an ArrayList.

public class Foo{    public String name, fname;    public Foo(String name, String fname){        this.name = name;        this.fname = fname;    }}

And then...

List<Foo> foos = new ArrayList<Foo>();foos.add(new Foo("demo","fdemo"));foos.add(new Foo("test","fname"));

So you can access them like...

foos.get(0).name;=> "demo"


You can accomplish this via Maps. Something like

Map<String, String>[] arr = new HashMap<String, String>[2]();arr[0].put("name", "demo");

But as you start using Java I am sure you will find that if you create a class/model that represents your data will be your best options. I would do

class Person{String name;String fname;}List<Person> people = new ArrayList<Person>();Person p = new Person();p.name = "demo";p.fname = "fdemo";people.add(p);