如何在Java中创建和获取关联数组,就像在PHP中一样?
例如:
$arr[0]['name'] = 'demo';
$arr[0]['fname'] = 'fdemo';
$arr[1]['name'] = 'test';
$arr[1]['fname'] = 'fname';
如何在Java中创建和获取关联数组,就像在PHP中一样?
例如:
$arr[0]['name'] = 'demo';
$arr[0]['fname'] = 'fdemo';
$arr[1]['name'] = 'test';
$arr[1]['fname'] = 'fname';
当前回答
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等价于Perl的散列
HashMap<Integer, HashMap<String, String>> hash;
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
实际上Java支持关联数组,它们被称为字典!
Object[][] data = {
{"mykey1", "myval1"},
{"mykey2", "myval2"},
{new Date(), new Integer(1)},
};
是的,这需要迭代搜索值的键,但如果你需要所有的,这将是最好的选择。
使用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}]