[英]JAVA How to create single and multi dimensional array
I am a beginner in java programming. 我是Java编程的初学者。
How do you create and initialize an array which contains a single and two dimensional array like below in an Arraylist or array by populating the value of each indexes within a for loop. 如何通过填充for循环中每个索引的值来创建和初始化一个数组,该数组包含一个或二维数组,如下所示在Arraylist或数组中。 any help will be much appreciated 任何帮助都感激不尽
{
"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",
}
}
The idea is to create an array that stores peoples information as seen above 想法是创建一个存储人员信息的数组,如上所述
You can create and initialize a 2D array in Java like this for your data. 您可以像这样用Java创建和初始化2D数组作为数据。
String[][] array = new String[][]{
{"john","20","blue","somewhere in the world","degree"},
{"ben","16", "green", "somewhere in the world", "secondary school"}
};
But for your data it could be better to have some data structure like follows. 但是对于您的数据,最好具有如下所示的一些数据结构。
Person.java 人.java
public class Person{
private String name;
private PersonDetails details;
//getters and setters
}
PersonDetails.java PersonDetails.java
public class PersonDetails{
private int age;
private String eyeColor;
private String location;
private String educationLevel;
//getters and setters
}
main function 主功能
List<Person> personsList = new ArrayList<>();
// loop starts
PersonDetails pd = new PersonDetails();
//set values
Person p = new Person();
//set values
personsList.add(p);
//loop ends
you can refer to this link: 您可以参考以下链接:
How to create a Multidimensional ArrayList in Java? 如何在Java中创建多维ArrayList?
create one multidimensional array list then change the string with T so it will be able to take objects 创建一个多维数组列表,然后用T更改字符串,以便能够接收对象
Your JSON has a bad syntax, the correct way is get a json like this 您的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"
}
]
}
The [
and ]
define an array of elements, and the {
and }
represents objects of your data type; [
和]
定义元素数组, {
和}
代表数据类型的对象; in this case people. 在这种情况下,人们。
Then you can get an array of ´people´ object with the necesary fields for information. 然后,您可以获取带有所需字段的“ people”对象数组,以获取信息。 I have this to serialize and deserialize java objects to json and visceversa, try this. 我有这个序列化和反序列化Java对象为json和visceversa,请尝试此。 Hope help you. 希望对你有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.