用Java中的现有数组创建二维数组 [英] Creating two Dimensional array with existing arrays in java

查看:68
本文介绍了用Java中的现有数组创建二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个字符串数组,我想创建一个由3列和动态行组成的二维数组。

I have four arrays of strings and I would like to create a two dimensional array of 3 columns and dynamic rows.

这些数组就像:

String[] first_name;
String[] last_name;
String[] unit;
String[] phone_number;


Object[][] obj = new Object[first_name.length()][3]

我的问题是如何实现以下目标:

My problem is how do I achieve something like this:

obj = {first_name[index] + " " + last_name[index], unit[index], phone_number[index]}

请帮忙!!!

推荐答案

我假设通过动态行来表示它取决于关于 first_name 数组中元素的数量。

I am assuming that by dynamic rows you mean that it depends on the number of elements in the first_name array.

所以您可以简单地迭代:

So you could simply iterate:

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];
}

但是,这种方法不是很好。您应该考虑创建一个名为 Employee 的对象,该对象作为3个字段,然后只有一个 Employee

However, this approach is not very good. You should consider creating an object for example named Employee which as the 3 fields, and then you just have an array of 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
}

然后有:

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]);
}

这篇关于用Java中的现有数组创建二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆