關於集合2-4作業
来源:2-4 编程练习
Heijyu
2023-04-02 17:53:53
老師,請問在最終打印employee的時候,是用toString()比較好還是用get方法比較好啊?在實際工作用哪個呀?
package com.imooc.collection.employee;
public class Employee {
protected int id;
protected static int nextId = 1;
protected String name;
protected double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
this.id = nextId;
nextId++;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
}package com.imooc.collection.employee;
import java.util.ArrayList;
import java.util.List;
public class EmployeeTest {
public static void main(String[] args) {
//定义ArrayList对象
List<Employee> employeeList = new ArrayList<>();
//创建三个Employee类的对象
Employee employee1 = new Employee("ZhangSan", 5000);
Employee employee2 = new Employee("LiSi", 5500);
Employee employee3 = new Employee("ZhaoLiu", 4000);
//添加员工信息到ArrayList中
employeeList.add(employee1);
employeeList.add(employee2);
employeeList.add(employee3);
//显示员工的姓名和薪资
for(Employee employee: employeeList){
System.out.println(employee);
}
}
}1回答
同学你好,同学的代码符合题目要求,逻辑清晰,书写规范,做的很棒。
实际工作中会更多的使用toString方法。
祝学习愉快~
相似问题