简体   繁体   中英

How to initialize an array of custom data type with more than 1 member variables?

Arrays of Primitive data types can be initialized like :

int a[] = {1 , 2, 3, 4, 5}; 

I have created a custom data type with a code like this -

class Student
{
    private String name;
    private int rollno;
}

I have created a Student array as given below :

Student s[] = new Student[5];
for(int i =0; i < s.length; s++)
    s[i] = new Student();

I want to initialize the member variables : name and rollno without taking user input. How can I do that? I want to do something like -

Student s[] = {("Sam", 21), ("Jules",3)...}

Assuming there's such constructor Student(String, int) , then you can try this:

Student[] studentArray = {
    new Student("Sam", 21),
    new Student("Jules",3)
};
Student s[] = {new Student("Sam", 21), new Student("Jules", 3)}

You can simply Initialize an array of custom data type by:


class struct{
int data;
String str;
}

// while creating an array ...
struct[] name = new struct[length];

// for inserting data ..
for( int i=0; i< length; i++){
   struct stk = new struct(); // create a new object to be stored..
   stk.str = "Priyansh Gupta from UPES Dehradun";   // declaring the values of the object we created
   stk.data = 2021;
   name[i] = stk;    // adding the object to the i'th index of array
}

// for printing the array
for( int i=0; i<length; i++){
   System.out.println(name[i].data); // printing the data of i'th index of array
   System.out.println(name[i].str); // print the string value of the index
}

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