如何在Java中创建和获取关联数组,就像在PHP中一样?

例如:

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

当前回答

在JDK 1.5 (http://tinyurl.com/3m2lxju)中甚至有一个注释:“注意:这个类已经过时了。新的实现应该实现Map接口,而不是扩展这个类。” 问候,N。

其他回答

看看Map接口和具体类HashMap。

创建一个Map:

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

添加一个键值对。

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

检索与某个键相关的值。

assoc.get("name")

当然,你可以创建一个map数组,因为这似乎是你想要的:

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

你可以通过地图来实现。类似的

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

但是当你开始使用Java时,我相信你会发现,如果你创建一个代表你的数据的类/模型将是你最好的选择。我会这么做

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

Java没有关联数组,你能得到的最接近的东西是Map接口

这是那个页面上的一个例子。

import java.util.*;

public class Freq {
    public static void main(String[] args) {
        Map<String, Integer> m = new HashMap<String, Integer>();

        // Initialize frequency table from command line
        for (String a : args) {
            Integer freq = m.get(a);
            m.put(a, (freq == null) ? 1 : freq + 1);
        }

        System.out.println(m.size() + " distinct words:");
        System.out.println(m);
    }
}

如果使用:

java Freq if it is to be it is up to me to delegate

你会得到:

8 distinct words:
{to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2}

好吧,我也在搜索关联数组,发现地图的列表作为最佳解决方案。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class testHashes {

public static void main(String args[]){
    Map<String,String> myMap1 = new HashMap<String, String>();

    List<Map<String , String>> myMap  = new ArrayList<Map<String,String>>();

    myMap1.put("URL", "Val0");
    myMap1.put("CRC", "Vla1");
    myMap1.put("SIZE", "Vla2");
    myMap1.put("PROGRESS", "Vla2");

    myMap.add(0,myMap1);
    myMap.add(1,myMap1);

    for (Map<String, String> map : myMap) {
        System.out.println(map.get("URL"));
    }

    //System.out.println(myMap);

}


}

在Java中没有关联数组这种东西。它最接近的亲戚是Map,它是强类型的,但是语法/API没有那么优雅。

这是基于你的例子你能得到的最接近的结果:

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