Java 实现类的实例
我对编程相当陌生,大约一年了,我已经到了一个逻辑缺口。假设我正在构建一个员工数据库:在没有硬编码employee1、employee2等的情况下,我如何创建员工实例 有人建议我使用数组,但在Java中,数组必须有一个固定的长度,所以我不确定如何实现这一点。任何帮助都会很好! -马特Java 实现类的实例,java,instance,multiple-instances,Java,Instance,Multiple Instances,我对编程相当陌生,大约一年了,我已经到了一个逻辑缺口。假设我正在构建一个员工数据库:在没有硬编码employee1、employee2等的情况下,我如何创建员工实例 有人建议我使用数组,但在Java中,数组必须有一个固定的长度,所以我不确定如何实现这一点。任何帮助都会很好! -马特 编辑:谢谢大家的帮助。我不知道ArrayList类型 您可以使用Employee类型的ArrayList ArrayList的大小可以更改。下面是一个向数组列表添加20个对象的简单循环: ArrayList<O
编辑:谢谢大家的帮助。我不知道ArrayList类型 您可以使用Employee类型的ArrayList
ArrayList的大小可以更改。下面是一个向数组列表添加20个对象的简单循环:
ArrayList<Object> array = new ArrayList<>();
for(int i =0; i < 20; i ++) {
array.add(new Object());
}
这是一种一次创建大量对象的简单方法,您不必指定大小,因此可以轻松更改ArrayList中包含的对象数量。在这种情况下,使用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);
}
创建一个类来保存员工信息
Employee.java
创建多个员工并打印他们的示例代码
Employees.java
因此,从本质上讲,只要在每次需要添加新员工时向数组中添加一个对象就可以了?@MatthewParnham-Yes。ArrayList可以更改大小。数组在创建时必须声明大小
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 + '\'' +
'}';
}
}
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'}