0

I try to create objects in a for loop like:

String[] empArr[] = {
    {"Moe","Jude","Employee","2017"},
    {"Noe","Joel","Employee","2019"},
    {"Poe","Juce","Employee","2021"}
};

Employee[] emp;
emp = new Employee[empArr.length];
        
// get length and loop from empArr[], here there are 3 entries
for (int i=0; i<=empArr.length-1; i++) {
    // get length and loop from empArr[i], here there are 4 entries
    for (int j=0; j<=empArr[i].length-1; j++) {
        // create objects in loop from empArr[i] with params from empArr[i][0 ]
        emp[i] = new Employee(empArr[i][0],empArr[i][1],empArr[i][2],empArr[i][3]);
    }

    // create from a method the output and get here all firstNames from empArr[]
    output(emp[i].getInfo("firstName"));
}

This is working and I get the output I want. But I use in the middle part at the moment:

for (int j=0; j<=empArr[i].length-1; j++) {
    emp[i] = new Employee(empArr[i][0],empArr[i][1],empArr[i][2],empArr[i][3]);
}

Is there a possibility to make a loop of j for the arguments of the object too? Something like:

emp[i] = new Employee(
    for (int j=0; j<=empArr[i].length-1; j++) {
        empArr[i][j];
    }
);

I tried this code above, but i cant get it working: I cant imagine a solution, hope for help

best regards

Big Sanch
  • 1
  • 1
  • 1
    No, there is no way to do this short of reflection - and you don't want to do that. The code wouldn't be shorter and would become harder to maintain, not easier. Trying to marshall data files (csvs, xmls, jsons, yamls) into objects is easy, just - not this way. Look up jackson, GSON, etc. – rzwitserloot Nov 24 '22 at 22:04
  • Thanks for your answer and tip, i will search for that – Big Sanch Nov 24 '22 at 22:07
  • I'd like to see Java get some ways to do this by default. Java has been able to marshal data with XML for a long time, I think it's time to add JSON to the default API. All that said, are you sure the second inner loop is needed? You just need to create four objects here, right? I think you're actually creating sixteen objects, each four a duplicate of the other. – markspace Nov 24 '22 at 22:11
  • @markspace an SO comment is not the appropriate venue for such sentiments. And, note that these discussions are already being held. The relevant mailing lists (this is probably core-lib-dev@openjdk) don't put much stock in 'me-tooism', or fly-by feature requests, so I doubt you'll get far suggesting it there :) - wheels are in motion, I don't think you need to add fuel to that particular fire, fortunately. – rzwitserloot Nov 25 '22 at 11:01

1 Answers1

0

Unless I miss-read this post (which could be likely), you can do it this way. Read the comments in code:

The Employee Class (you didn't post yours):

public class Employee {

    private String firstName;
    private String lastName;
    private String employeeStatus;
    private String yearOfHire;
    
    // An Employee class Constructor specific to the desired need:
    public Employee(String firstName, String lastName, 
                    String employeeStatus, String yearOfHire) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.employeeStatus = employeeStatus;
        this.yearOfHire = yearOfHire;
    }
    
    //GETTERS & SETTERS
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmployeeStatus() {
        return employeeStatus;
    }

    public void setEmployeeStatus(String employeeStatus) {
        this.employeeStatus = employeeStatus;
    }

    public String getYearOfHire() {
        return yearOfHire;
    }

    public void setYearOfHire(String yearOfHire) {
        this.yearOfHire = yearOfHire;
    }

    @Override
    public String toString() {
        return firstName + ", " + lastName + ", " + employeeStatus + ", " + yearOfHire;
    }
}

The code to use the above Employee class:

String[][] empArr = {
        {"Moe","Jude","Employee","2017"},
        {"Noe","Joel","Employee","2019"},
        {"Poe","Juce","Employee","2021"}
    };
  
// Declare a List to hold instances of Employee: 
List<Employee> employeeInstances = new ArrayList<>();
    
/* Variables to be filled from 2D Array and passed 
   to Employee constructor:             */
String fName, lName, emplStatus, hireYear;
    
// Iterate 2D Array Rows:
for (String[] ary : empArr) {
    // Default string variables with "N/A" (Not Available): 
    fName = "N/A"; lName = "N/A"; 
    emplStatus = "N/A"; hireYear = "N/A";
    /* Iterate through the current inner Array (row) and fill 
       above variables to use in Employee constructor: */
    for (int i = 0; i < ary.length; i++) {
        /* Use 'Ternary Operator' to handle Array elements 
           that are Null String (""):               */
        fName =      !ary[0].isEmpty() ? ary[0] : fName;
        lName =      !ary[1].isEmpty() ? ary[1] : lName;
        emplStatus = !ary[2].isEmpty() ? ary[2] : emplStatus;
        hireYear =   !ary[3].isEmpty() ? ary[3] : hireYear;
    }
    // Create and Add an instance of Employee to the employeeInstances List:
    employeeInstances.add(new Employee(fName, lName, emplStatus, hireYear));
}
    
/* Do whatever you want with the instances of Employee contained
   within the employeeInstances List, for example: */
    
System.out.println("List all employees to Console Window:");
// Iterate through the employeeInstances List:
for (Employee empl : employeeInstances) {
    // Display data for current Employee instance:
    System.out.println(empl.toString());
}
System.out.println();
    
System.out.println("List all employees first and last names "
                 + "to Console Window:");
// Iterate through the employeeInstances List:
for (Employee empl : employeeInstances) {
    /* Display the first and last name of each Employee instance
       contained within the employeeInstances List. Employee class
       Getter methods are used to get the First and Last names from
       the current instance:              */
    System.out.println(empl.getFirstName() + " " + empl.getLastName());
}

Console Window should display:

List all employees to Console Window:
Moe, Jude, Employee, 2017
Noe, Joel, Employee, 2019
Poe, Juce, Employee, 2021

List all employees first and last names to Console Window:
Moe Jude
Noe Joel
Poe Juce
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22