Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating two Dimensional array with existing arrays in java

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

the arrays are like:

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

Please help out!!!

like image 355
Gordons Avatar asked Dec 19 '12 14:12

Gordons


People also ask

How do you combine two multidimensional arrays in Java?

In order to merge two arrays, we find its length and stored in fal and sal variable respectively. After that, we create a new integer array result which stores the sum of length of both arrays. Now, copy each elements of both arrays to the result array by using arraycopy() function.

How do you create a double 2D array in Java?

To create a two dimensional array in Java, you have to specify the data type of items to be stored in the array, followed by two square brackets and the name of the array. Here's what the syntax looks like: data_type[][] array_name; Let's look at a code example.

How do you add two-dimensional arrays?

Declare and initialize 2 two-dimensional arrays a and b. Calculate the number of rows and columns present in the array a (as dimensions of both the arrays are same) and store it in variables rows and cols respectively. Declare another array sum with the similar dimensions. Display the elements of array sum.


1 Answers

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

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

For example:

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
}

And then you just have:

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]);
}
like image 146
jbx Avatar answered Oct 05 '22 07:10

jbx