简体   繁体   中英

JAVA How to create single and multi dimensional array

I am a beginner in java programming.

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. 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.

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

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
}

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?

create one multidimensional array list then change the string with T so it will be able to take objects

Your JSON has a bad syntax, the correct way is get a json like this

{
"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. I have this to serialize and deserialize java objects to json and visceversa, try this. Hope help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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