0

我基本上是一个 php 程序员,现在只是想知道(或徘徊!)在 java 海的岸边。当然还有救生艇,stackoverflow。

我正在努力在 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 示例阐明所需的数组

4

3 回答 3

4

在 Java 中这样的代码的良好实践不是为此使用无类型数组,而是创建实际的类型对象:

class Whatever {
  private final String username;
  private final List<Group> groups;
  ...
}
class Group {
  ...
}
于 2013-08-29T17:04:30.067 回答
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 
    } 
于 2013-08-29T17:11:50.193 回答
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"));

您可以将数组元素设置为数组、ArrayLists 或其他Map<String,Object>映射,从而获得您的多维数组。问题是,Java 是强类型的,这意味着该get方法将返回一个 Object,并且您必须将其强制转换为您期望的类型:

String[] categories = (String[])(arr.get ("categories"));

或者

ArrayList<String> categories = (ArrayList<String>)(arr.get ("categories"));

如果先前为“类别”存储的对象类型错误,则会引发异常。

如果不出意外,您至少应该查看集合教程,因为如果您将使用 Java,您肯定需要了解这些内容。

[注意:我还没有测试过上面的任何代码。我想我是对的。]

于 2013-08-29T17:35:33.537 回答