如何在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';
当前回答
看看Map接口和具体类HashMap。
创建一个Map:
Map<String, String> assoc = new HashMap<String, String>();
添加一个键值对。
assoc.put("name", "demo");
检索与某个键相关的值。
assoc.get("name")
当然,你可以创建一个map数组,因为这似乎是你想要的:
Map<String, String>[] assoc = ...
其他回答
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}
看看Map接口和具体类HashMap。
创建一个Map:
Map<String, String> assoc = new HashMap<String, String>();
添加一个键值对。
assoc.put("name", "demo");
检索与某个键相关的值。
assoc.get("name")
当然,你可以创建一个map数组,因为这似乎是你想要的:
Map<String, String>[] assoc = ...
关于PHP评论“不,PHP不会喜欢它”。实际上,除非您设置了一些非常严格的异常/错误级别(甚至可能没有设置),否则PHP将继续运行。
默认情况下,访问一个不存在的变量/越界数组元素会“取消”你正在赋值的值。NO,它不是空的。据我所知,PHP继承了Perl/C。所以有:未设置和不存在的变量,值是设置但为NULL,布尔值为False,还有标准语言中所有的东西。你必须分别测试这些,或者选择正确的函数/语法内建的计算。
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
Object[][] data = {
{"mykey1", "myval1"},
{"mykey2", "myval2"},
{new Date(), new Integer(1)},
};
是的,这需要迭代搜索值的键,但如果你需要所有的,这将是最好的选择。