Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

java - Convert a string array to an object array

I have a String array contains name, age, and gender of 10 customers. I tried to convert it to Customer array. I tried to copy each elements of String array into Customer array but it's not compatible. How do I insert elements from String array into Customer array?

//String[] customerData is given but too long to copy
Customer[] custs = new Customer[numberOfCustomer];
for (int x = 0; x < customerData.length; x++) {
    custs[x] = customerData[x];
}
question from:https://stackoverflow.com/questions/66054646/convert-a-string-array-to-an-object-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming that Customer class has an all-args constructor Customer(String name, int age, String gender) and the input array contains all the fields like:

String[] data = {
    "Name1", "25", "Male",
    "Name2", "33", "Female",
// ...
};

The array of customers may be created and populated like this:

Customer[] customers = new Customer[data.length / 3];
for (int i = 0, j = 0; i < customers.length && j < data.length; i++, j += 3) {
    customers[i] = new Customer(data[j], Integer.parseInt(data[j + 1]), data[j + 2]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...