我创建了一个类employee。它有四个变量name,id,salary,city。我已经制作了employee类对象的数组列表。当我运行该文件时,它只显示默认值。但我想在我的数组列表中添加多个值。我该怎么办?请帮我解决这个问题,这是我的代码
import java.util.*;
public class arraylist {
public static void main(String[] args) {
new arraylist();
}
public arraylist() {
List<Employee > listOfEmp = new ArrayList<Employee >();
Employee bk1 = new Employee ();
listOfEmp .add(bk1);
System.out.println(" emp = " + bk1);
System.out.println("listOfEmployee(0) = " + listOfEmp.get(0));
}
public class Employee {
String name="sarah";
int id =102;
String city="orny";
int salary=13000;
// @Override
public String toString() {
return "Employee: name = " + name + "; Id = " + id + "; City = " + city + "; Salary = " + salary + "; hashCode = " + hashCode();
}
}
}
最佳答案
您已经创建了具有默认字段值的 Employee 类。
您尚未定义任何参数化构造函数或 setter 来保存新的 Employee。看看如何做到这一点:
使用构造函数添加员工;迭代并打印员工列表:
List<Employee> listOfEmp = new ArrayList<Employee>();
// Add employee to list
listOfEmp.add(new Employee("sarah1", 101, "orny", 13000));
listOfEmp.add(new Employee("sarah2", 102, "orny", 13000));
listOfEmp.add(new Employee("sarah3", 103, "orny", 13000));
// Iterate and print employee list
for (Employee employee : listOfEmp)
System.out.println(employee);
在 Employee 类中添加参数化构造函数:
class Employee {
private String name;
private int id;
private String city;
private int salary;
public Employee(String name, int id, String city, int salary) {
this.name = name;
this.id = id;
this.city = city;
this.salary = salary;
}
// @Override
public String toString() {
return "Employee: name = " + name + "; Id = " + id + "; City = " + city
+ "; Salary = " + salary;
}
}
您还可以定义 setter 方法[在 Employee 类中]来保存实例变量的值。
关于java - 在数组列表中添加多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30974960/