Java associative-array

290,019

Solution 1

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

Solution 2

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"

Solution 3

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

Solution 4

Look at the Map interface, and at the concrete class HashMap.

To create a Map:

Map<String, String> assoc = new HashMap<String, String>();

To add a key-value pair:

assoc.put("name", "demo");

To retrieve the value associated with a key:

assoc.get("name")

And sure, you may create an array of Maps, as it seems to be what you want:

Map<String, String>[] assoc = ...

Solution 5

There is no such thing as associative array in Java. Its closest relative is a Map, which is strongly typed, however has less elegant syntax/API.

This is the closest you can get based on your example:

Map<Integer, Map<String, String>> arr = 
    org.apache.commons.collections.map.LazyMap.decorate(
         new HashMap(), new InstantiateFactory(HashMap.class));

//$arr[0]['name'] = 'demo';
arr.get(0).put("name", "demo");

System.out.println(arr.get(0).get("name"));
System.out.println(arr.get(1).get("name"));    //yields null
Share:
290,019

Related videos on Youtube

dobs
Author by

dobs

Updated on July 04, 2020

Comments

  • dobs
    dobs almost 4 years

    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';
    
  • Tomasz Nurkiewicz
    Tomasz Nurkiewicz over 13 years
    This will throw NullPointerException if outer map does not contain map for entry 0. Isn't PHP more permissive with $arr[0]['name'] (I don't know this language at all)?
  • Felix Kling
    Felix Kling about 13 years
    If you refer to download.oracle.com/javase/1.4.2/docs/api/java/util/… then note that this class is (a) abstract and (b) deprecated.
  • Lemon
    Lemon almost 13 years
    PHP wouldn't like it if you tried to access a key that doesn't exist, no :)
  • Lemon
    Lemon almost 13 years
    What's the LazyMap.decorate and InstantiateFactory and stuff for?
  • frostymarvelous
    frostymarvelous over 12 years
    I think I like this method better thanks. Coming from php where everything is so simple is sort of awkward using java, but great solution. Thanks.
  • Adam Arold
    Adam Arold almost 12 years
    Why are you using LinkedList? It's not a problem, I'm just curious.
  • Johan Sjöberg
    Johan Sjöberg almost 12 years
    @edem, some implementation was necessary. Today however, I would prefer ArrayList in almost all cases due to (unexpected?) performance differences. But that's another discussion.
  • demongolem
    demongolem almost 12 years
    +1 All the other answers seem to assume that one of the "keys" is an integer. What if the associate array was based upon two non-integer keys (a tuple we would say in python)? I believe you would need to use this approach as indexing becomes impossible.
  • Marcus
    Marcus over 11 years
    Never forget to initialise the exact hash size and set the load factor as 1: HashMap<String, String>(capacity, 1). Otherwise you may implement a huge overhead and your objects needs to much RAM. +1 for ArrayList, but why no edit of the answer?
  • Francisco Corrales Morales
    Francisco Corrales Morales about 10 years
    but, what if the value must have a value that is not a String ?
  • Francisco Corrales Morales
    Francisco Corrales Morales about 10 years
    why do you say that the second option is more accurate ?
  • Johan Sjöberg
    Johan Sjöberg about 10 years
    @FranciscoCorralesMorales, you can replace string with any object that meet your needs. It's not that it's more accurate, but the second example closer matches what OP is asking for.
  • Sobiaholic
    Sobiaholic over 9 years
    Why use List instead of ArrayList? a java newbie here.
  • veta
    veta almost 9 years
    'List' is an abstract class and 'ArrayList' is one of the implementations of that class, there are other type of lists derived from the same abstract class. So because of this an ArrayList is also a List. You cannot create an instance of an abstract class, just use it as type here, you need to use the implementation for your instances. So the List is the type, and ArrayList is the instance here.
  • Ar5hv1r
    Ar5hv1r over 8 years
    @Marcus "Never forget to initialise the exact hash size and set the load factor as 1" - where do you get that advice? You should almost never specify the load-factor of a HashMap, and certainly not without intentionally benchmarking the behavior and finding a better load-factor for your use case. The only reason to specify an initial size is if you know in advance that the map will be very large. HashMap does not waste (much) memory if empty, but if you intend to create a large map you can save several array-resizes by specifying it's size up front.
  • Matthew
    Matthew almost 8 years
    The Map.containsKey() method iterates through all the Map's keys, and so does the Map.get() method which also naturally returns a value when the key is found. So just Map.get() performs both those techniques, only once (so more performant), without writing this new code. Also Map.get() returns the value associated with the first key matched, and then stops searching, which is faster and the familiar behavior for this pattern. The code in this post keeps iterating through all the keys even after the search key is matched, and returns the last matched key (not the first matched key).
  • windmaomao
    windmaomao almost 4 years
    I don't understand, how do you access things by a key here, i thought this is the main point of having associative array.
  • Jeremy
    Jeremy over 3 years
    @windmaomao You don't. That's why the accepted answer is to use a Map.
  • durette
    durette over 3 years
    An associative array is dynamic and flexible. New attributes can be added at runtime. A Java class has a predefined set of instance variables, set a compile time.