
本文介绍了如何使用循环动态地创建对象,并使用数组中的数据作为构造函数的参数。通过示例代码展示了如何避免嵌套循环,并使用列表存储创建的对象,最后演示了如何访问和使用这些对象。
在Java编程中,经常需要根据一组数据动态地创建对象。例如,从数据库或文件中读取了一组用户信息,需要为每个用户创建一个Employee对象。本文将详细介绍如何使用循环来实现这一目标,并提供清晰的代码示例和注意事项。
首先,我们需要定义一个 Employee 类,该类包含员工的各种信息,例如姓名、职位和入职年份。
public class Employee {
private String firstName;
private String lastName;
private String employeeStatus;
private String yearOfHire;
public Employee(String firstName, String lastName, String employeeStatus, String yearOfHire) {
this.firstName = firstName;
this.lastName = lastName;
this.employeeStatus = employeeStatus;
this.yearOfHire = yearOfHire;
}
// Getters and setters (省略)
@Override
public String toString() {
return firstName + ", " + lastName + ", " + employeeStatus + ", " + yearOfHire;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}假设我们有一个二维字符串数组,其中每一行代表一个员工的信息:
String[][] empArr = {
{"Moe","Jude","Employee","2017"},
{"Noe","Joel","Employee","2019"},
{"Poe","Juce","Employee","2021"}
};我们的目标是使用这个数组中的数据创建 Employee 对象。一种常见的做法是使用循环遍历数组,并为每一行创建一个对象。为了更灵活地存储这些对象,我们使用 ArrayList。
import java.util.ArrayList;
import java.util.List;
public class EmployeeCreator {
public static void main(String[] args) {
String[][] empArr = {
{"Moe","Jude","Employee","2017"},
{"Noe","Joel","Employee","2019"},
{"Poe","Juce","Employee","2021"}
};
List<Employee> employeeInstances = new ArrayList<>();
String fName, lName, emplStatus, hireYear;
for (String[] ary : empArr) {
fName = "N/A"; lName = "N/A";
emplStatus = "N/A"; hireYear = "N/A";
for (int i = 0; i < ary.length; i++) {
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;
}
employeeInstances.add(new Employee(fName, lName, emplStatus, hireYear));
}
// 遍历 Employee 列表
System.out.println("List all employees to Console Window:");
for (Employee empl : employeeInstances) {
System.out.println(empl.toString());
}
System.out.println();
System.out.println("List all employees first and last names to Console Window:");
for (Employee empl : employeeInstances) {
System.out.println(empl.getFirstName() + " " + empl.getLastName());
}
}
}这段代码首先创建了一个 ArrayList 来存储 Employee 对象。然后,它遍历 empArr 数组,并为每一行创建一个 Employee 对象,并将该对象添加到列表中。
在上面的代码中,使用了三元运算符来避免数组越界。如果数组中的某个元素为空字符串,则使用默认值 "N/A"。
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;
本文介绍了如何使用循环动态地创建对象,并使用数组中的数据作为构造函数的参数。通过使用 ArrayList,我们可以更灵活地存储和管理这些对象。在实际开发中,可以根据需要修改代码,例如从数据库或文件中读取数据,或者使用不同的数据结构来存储对象。在处理数组数据时,务必注意数组越界问题,并采取相应的措施来避免错误。
以上就是使用循环创建带参数的对象的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号