我对编程很新(大约一年),而且我遇到了逻辑上的差距。假设我正在构建员工数据库:如何在不对员工1,员工2等进行硬编码的情况下创建员工实例。
我被建议使用数组,但在Java中,数组必须有一个设置长度,所以我不确定如何实现这一点。任何帮助都会很棒! -Matt
编辑:感谢大家的帮助。我不知道ArrayList类型!
答案 0 :(得分:1)
ArrayLists可以改变大小。这是一个将20个对象添加到数组List的简单循环:
ArrayList<Object> array = new ArrayList<>();
for(int i =0; i < 20; i ++) {
array.add(new Object());
}
这是一种简单的方法,可以一次创建大量对象,而且您不必具有指定的大小,因此您可以轻松更改ArrayList
答案 1 :(得分:0)
您可以使用Employee
类型的ArrayListhttps://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
答案 2 :(得分:0)
使用ArrayList
(在这种情况下无需指定列表的长度)
List<Employee> employees = new ArrayList<>();
while (resultSet.next()) {
Employee employee = new Employee();
employee.setId(resultSet.getInt("id"));
employee.setFirstname(resultSet.getString("firstname"));
.....
employees.add(employee);
}
答案 3 :(得分:0)
创建一个类来保存员工信息。
Employee.java
public class Employee {
String firstName;
String lastName;
String deptName;
public Employee() {
}
public Employee(String firstName, String lastName, String deptName) {
this.firstName = firstName;
this.lastName = lastName;
this.deptName = deptName;
}
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 getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
@Override
public String toString() {
return "Employee{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", deptName='" + deptName + '\'' +
'}';
}
}
创建多名员工并打印出来的示例代码
Employees.java
import java.util.ArrayList;
import java.util.List;
public class Employees {
public static void main(String[] args) {
List<Employee> employeeList = new ArrayList<>();
employeeList.add(new Employee("FN-1","LN-1","Dept-1"));
employeeList.add(new Employee("FN-2","LN-2","Dept-2"));
employeeList.add(new Employee("FN-3","LN-3","Dept-3"));
//loop
for (int i = 4; i < 8; i++) {
employeeList.add(new Employee("FN-" + i, "LN-" + i, "Dept-" + i));
}
//print
employeeList.forEach(System.out::println);
}
}
<强>输出:强>
Employee{firstName='FN-1', lastName='LN-1', deptName='Dept-1'}
Employee{firstName='FN-2', lastName='LN-2', deptName='Dept-2'}
Employee{firstName='FN-3', lastName='LN-3', deptName='Dept-3'}
Employee{firstName='FN-4', lastName='LN-4', deptName='Dept-4'}
Employee{firstName='FN-5', lastName='LN-5', deptName='Dept-5'}
Employee{firstName='FN-6', lastName='LN-6', deptName='Dept-6'}
Employee{firstName='FN-7', lastName='LN-7', deptName='Dept-7'}