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

例如:

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

当前回答

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}

其他回答

关于PHP评论“不,PHP不会喜欢它”。实际上,除非您设置了一些非常严格的异常/错误级别(甚至可能没有设置),否则PHP将继续运行。

默认情况下,访问一个不存在的变量/越界数组元素会“取消”你正在赋值的值。NO,它不是空的。据我所知,PHP继承了Perl/C。所以有:未设置和不存在的变量,值是设置但为NULL,布尔值为False,还有标准语言中所有的东西。你必须分别测试这些,或者选择正确的函数/语法内建的计算。

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

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,它是强类型的,但是语法/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

Java不像PHP那样有关联数组。

对于您正在做的事情,有各种解决方案,例如使用Map,但这取决于您想如何查找信息。您可以轻松地编写一个类来保存所有信息,并将它们的实例存储在ArrayList中。

public class Foo{
    public String name, fname;

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

然后……

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

所以你可以像…

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

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}