老师可以检查一下这里为什么报错了吗?
来源:2-4 编程练习
刘徽
2023-04-29 11:05:07
在这里输入代码
public class EmployeeTest {
public static void main(String[] args) {
//定义ArrayList对象
ArrayList employeeList = new ArrayList();
//创建三个Employee类的对象
Employee e1 = new Employee("张三",5000.0);
Employee e2 = new Employee("李四",5500.0);
Employee e3 = new Employee("赵六",4000.0);
//添加员工信息到ArrayList中
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
//显示员工的姓名和薪资
System.out.println("员工姓名\t员工薪资");
for(Employee employee: employeeList){
System.out.println();
}
}
}
在这里输入代码
public class Employee {
//根据需求完成Employee类的定义
int id;
String name;
double salary;
public Employee() {
}
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
1回答
ArrayList<Employee> employeeList = new ArrayList<>();
因为使用不使用泛型<>定义的ArrayList集合,里面的元素默认为Object类型,所以Employee爆红是因为Employee类型与Object类型不匹配,在使用集合时,尽量使用泛型来约束元素的类型.
相似问题