繁体   English   中英

JAVA如何创建一维和多维数组

[英]JAVA How to create single and multi dimensional array

我是Java编程的初学者。

如何通过填充for循环中每个索引的值来创建和初始化一个数组,该数组包含一个或二维数组,如下所示在Arraylist或数组中。 任何帮助都感激不尽

{
"john":  
      {  
         "age":"20",
         "eye color":"blue",
         "location":"somewhere in the world",
         "education-level":"degree",
       }

"ben" : 
      {  
         "age":"16",
         "eye color":"green",
         "location":"somewhere in the world",
         "education-level":"secondary school",
       }

}

想法是创建一个存储人员信息的数组,如上所述

您可以像这样用Java创建和初始化2D数组作为数据。

String[][] array = new String[][]{
        {"john","20","blue","somewhere in the world","degree"},
        {"ben","16", "green", "somewhere in the world", "secondary school"}         
    };

但是对于您的数据,最好具有如下所示的一些数据结构。

人.java

public class Person{
    private String name;
    private PersonDetails details;
//getters and setters
}

PersonDetails.java

public class PersonDetails{
    private int age;
    private String eyeColor;
    private String location;
    private String educationLevel;
//getters and setters
}

主功能

List<Person> personsList = new ArrayList<>();
// loop starts
PersonDetails pd = new PersonDetails();
//set values
Person p = new Person();
//set values
personsList.add(p);
//loop ends

您可以参考以下链接:

如何在Java中创建多维ArrayList?

创建一个多维数组列表,然后用T更改字符串,以便能够接收对象

您的JSON语法错误,正确的方法是获取像这样的json

{
"people" : 
[
    {  "name":"john",
        "age":"20",
        "eye color":"blue",
        "location":"somewhere in the world",
        "education-level":"degree"
    },
    {  
        "name":"ben",
        "age":"16",
        "eye color":"green",
        "location":"somewhere in the world",
        "education-level":"secondary school"
    }
]
}

[]定义元素数组, {}代表数据类型的对象; 在这种情况下,人们。

然后,您可以获取带有所需字段的“ people”对象数组,以获取信息。 我有这个序列化和反序列化Java对象为json和visceversa,请尝试此。 希望对你有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM