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

例如:

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

当前回答

看看Map接口和具体类HashMap。

创建一个Map:

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

添加一个键值对。

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

检索与某个键相关的值。

assoc.get("name")

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

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

其他回答

Object[][] data = {
{"mykey1", "myval1"},
{"mykey2", "myval2"},
{new Date(), new Integer(1)},
};

是的,这需要迭代搜索值的键,但如果你需要所有的,这将是最好的选择。

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

使用ArrayList < Map < String, String > >

下面是一个代码示例:

ArrayList<Map<String, String>> products = new ArrayList<Map<String, String>>();
while (iterator.hasNext()) {
         Map<String, String> product = new HashMap<String, String>();
         Element currentProduct = iterator.next();
         product.put("id",currentProduct.get("id"));
         product.put("name" , currentProduct.get("name") );
         products.add(product );
}
System.out.println("products : " + products);

输出:

产品:[{id=0001, name=prod1}, {id=0002, name=prod2}]

Java中的关联数组与PHP中的类似:

SlotMap hmap = new SlotHashMap();
String key = "k01";
String value = "123456";
// Add key value
hmap.put( key, value );

// check if key exists key value
if ( hmap.containsKey(key)) {
    //.....        
}

// loop over hmap
Set mapkeys =  hmap.keySet();
for ( Iterator iterator = mapkeys.iterator(); iterator.hasNext();) {
  String key = (String) iterator.next();
  String value = hmap.get(key);
}

更多信息,请参见类SoftHashMap: https://shiro.apache.org/static/1.2.2/apidocs/org/apache/shiro/util/SoftHashMap.html