簡體   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