Gor*_*ons 5 java arrays codenameone
我有四个字符串数组,我想创建一个3列和动态行的二维数组.
数组如下:
String[] first_name;
String[] last_name;
String[] unit;
String[] phone_number;
Object[][] obj = new Object[first_name.length()][3]
Run Code Online (Sandbox Code Playgroud)
我的问题是如何实现这样的目标:
obj = {first_name[index] + " " + last_name[index], unit[index], phone_number[index]}
Run Code Online (Sandbox Code Playgroud)
请帮忙!!!
我假设动态行意味着它取决于 first_name数组中元素的数量。
所以你可以简单地迭代:
String[][]obj = new String[first_name.length][3];
for (int i = 0; i < first_name.length; i++)
{
obj[i][0] = first_name[i] + " " + last_name[i];
obj[i][1] = unit[i];
obj[i][2] = phone_number[i];
}
Run Code Online (Sandbox Code Playgroud)
然而,这种做法并不是很好。您应该考虑创建一个对象,例如将Employee其命名为 3 个字段,然后您就拥有一个数组Employee
例如:
public class Employee
{
String name;
String unit;
String phoneNumber;
public Employee(String name, String unit, String phoneNumber)
{
//... rest of constructor to copy the fields
}
//... setters and getters
}
Run Code Online (Sandbox Code Playgroud)
然后你就拥有了:
Employee[] employees = new Employee[first_name.length];
for (int i = 0; i < first_name.length; i++)
{
employees[i] = new Employee(first_name[i] + " " + last_name[i], unit[i], phone_number[i]);
}
Run Code Online (Sandbox Code Playgroud)