Java ArrayList为其添加employee方法和getter方法
我想为arraylist做一个setter和getter。 我做错了什么Java ArrayList为其添加employee方法和getter方法,java,arraylist,Java,Arraylist,我想为arraylist做一个setter和getter。 我做错了什么 // Method to add employee public void addEmployee(Employee newGuy) { this.employee = newGuy; } // Method to get new employee public Employee getEmployees() { return employee;
// Method to add employee
public void addEmployee(Employee newGuy)
{
this.employee = newGuy;
}
// Method to get new employee
public Employee getEmployees()
{
return employee;
}
this.employee=newGuy;
this.employee=newGuy;
如果您要返回一名新员工,则必须创建一名新员工,如下所示:
public Employee getEmployees(){
return new Employee();
}
this.employee=newGuy;
这样,就可以为ArrayList()创建setter和getter
this.employee=newGuy;
ArrayList employees=new ArrayList();
公共阵列列表getEmployees(){
返回员工;
}
公共员工(ArrayList员工){
这是。雇员=雇员;
}
而不是
this.employee=newGuy;
使用
this.employee=newGuy;
列表的setter和getter不能像您认为的那样工作
this.employee=newGuy;
二传手和接球手可以这样工作
this.employee=newGuy;
public void setEmployee(ArrayList<Employee> employees)
{
this.employees = employees;
}
public List<Employee> getEmployees()
{
return employees;
}
getter需要一个要查找的员工的索引。这也可以通过不同的键来完成。例如,见
this.employee=newGuy;
使用列表
与直接使用条目(在本例中是员工
)不同。列表
可以容纳从无到多的员工。我建议从JavaAPI中读取。我还建议查看使用列表
和映射
接口的不同方法的示例。我遇到了一个不兼容的类型错误。员工无法转换为ArrayList我如何解决此问题,我是否需要转换或汇总您应该编辑您的问题,而不是对其进行评论。如何定义成员<代码>公共雇员代码>周围的类是什么?你应该发布更多信息。employee.add(newGuy)代码>好的,谢谢。然后,要在getter中返回它,我只需执行以下操作:返回员工?是的,这就是您必须执行的所有操作。public void setEmployees(List employees){this.employees=employees;}//获取一个错误:不兼容的类型:List无法转换为ArrayList,//我遵循了上面的代码,但仍然得到了这个error@DanielMcHenry将setEmployees(列出员工)
更改为setEmployees(arraylistemployees)
以修复它。谢谢好的,现在我还有两种方法需要包括。一个sortByName()方法,在说明中告诉我需要使用Comparator接口对象和sort by salary,并提示使用Collections.sort(),因此我需要更改类签名以实现Comparator接口。比如:公共类CompanyDataBase实现Comparatory您必须说您所在的类实现Comparator。正确//按名称比较的方法公共列表sortByName(ArrayList employees){public int compare(emp e1,emp e2){if(e1.getName() this.employee=newGuy;