我正努力在java中创建一个多维数组,就像在php中一样,它很简单$array["bla"]["blabla"]["blablabla"]...
这就是我想要实现的目标
Array
(
[user] => UserName
[groups] => Array
(
[0] => group1
[1] => group2
[2] => group3
)
[categories] => Array
(
[0] => category1
[1] => category2
[2] => category3
)
[notification] => user notification string
[departments] => Array
(
[0] => department1
[1] => department2
[2] => department3
[3] => department4
)
[sub-deptmnt] => Array
(
[department1] => Array
(
[0] => subdep1
[1] => subdep2
)
[department2] => Array
(
[0] => another-subdep1
[1] => another-subdep2
[2] => another-subdep3
)
)
)
php中的是
$array["user"] = "UserName";
$array["groups"] = array("group1","group2","group3");
$array["categories"] =array("category1","category2","category3");
$array["notification"] = "user notification string";
$array["departments"] = array("department1","department2","department3","department4");
$array["sub-deptmnt"] = array("department1" => array("subdep1","subdep2"),"department2"=> array("another-subdep1","another-subdep2", "another-subdep3"));
有人请帮我继续......
编辑:使用php示例澄清所需的数组
答案 0 :(得分:4)
Java中这样的代码的良好实践不是为此使用无类型数组,而是为了生成实际类型的对象:
class Whatever {
private final String username;
private final List<Group> groups;
...
}
class Group {
...
}
答案 1 :(得分:1)
像这样定义你的对象
class SampleModel{
String userName;
List<String> groups ;
List<String> categories;
String notification;
List<String> departments;
Map<String,List<String>> sub_deptmnt;
//getter and setter
}
答案 2 :(得分:0)
如果你事先知道密钥是什么,那么最好用Prabhakaran向你展示的方式设置一个带有字段和getter / setter方法的类。
如果键可以是动态的,那么:相当于PHP的关联数组是Map<String,Object>
。
Map<String,Object> arr = new HashMap<String,Object> ();
然后创建一个数组元素:
arr.put ("user", userName);
并检索它:
String userName = (String)(arr.get ("user"));
您可以将数组元素设置为数组,或ArrayList
s或其他Map<String,Object>
映射,从而获得多维数组。但问题是Java是强类型的,这意味着get
方法将返回一个Object,你必须将它强制转换为你期望的类型:
String[] categories = (String[])(arr.get ("categories"));
或
ArrayList<String> categories = (ArrayList<String>)(arr.get ("categories"));
如果先前为“categories”存储的对象的类型错误,则会抛出异常。
如果不出意外,您至少应该查看collections tutorial,因为如果您将使用Java,您肯定需要知道这些内容。
[注意:我还没有测试过任何上述代码。我想我做对了。]