
本文旨在讲解如何使用循环结构,特别是`for`循环,在Java中动态创建对象并利用数组中的数据作为构造函数的参数。通过示例代码,我们将展示如何有效地从二维数组中提取数据,并将其用于创建`Employee`对象的实例,最后将这些对象存储在列表中。
在Java编程中,经常需要根据一组数据动态创建对象。当数据存储在数组中,特别是二维数组中时,使用循环结构可以简化对象的创建过程。本教程将详细介绍如何利用for循环从二维数组中提取数据,并将其作为参数传递给对象的构造函数,从而实现对象的动态创建。
首先,我们需要定义一个Employee类,该类包含员工的基本信息,如firstName, lastName, employeeStatus, yearOfHire。
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;
}
}这个类定义了四个私有属性,并提供了一个构造函数来初始化这些属性。toString()方法用于返回对象的字符串表示形式,方便输出和调试。此外,还添加了firstName和lastName的getter方法,方便后续操作。
立即学习“Java免费学习笔记(深入)”;
假设我们有一个二维字符串数组,其中每一行代表一个员工的信息:
String[][] empArr = {
{"Moe","Jude","Employee","2017"},
{"Noe","Joel","Employee","2019"},
{"Poe","Juce","Employee","2021"}
};现在,我们需要遍历这个数组,为每一行数据创建一个Employee对象。
import java.util.ArrayList;
import java.util.List;
public class Main {
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));
}
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对象。然后,使用增强型for循环遍历empArr数组的每一行。在内部循环中,使用三元运算符确保即使数组元素为空字符串,也能赋予默认值"N/A",避免空指针异常。最后,使用提取的数据创建一个新的Employee对象,并将其添加到列表中。
通过本教程,你已经掌握了如何使用循环结构在Java中动态创建对象,并利用数组中的数据作为构造函数的参数。希望这些知识能帮助你在实际编程中更加灵活地处理对象创建的问题。
以上就是使用循环创建对象并传递参数的Java教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号