Java 如何在集合类中使用此选项
如何使用此关键字引用从ArrayList继承的类中的集合,如下所示。我在设计时出错,IDE不允许我编译代码Java 如何在集合类中使用此选项,java,list,collections,this,Java,List,Collections,This,如何使用此关键字引用从ArrayList继承的类中的集合,如下所示。我在设计时出错,IDE不允许我编译代码 public class Company{ private EmployeeCollection employees; public Company(){ this.employees = new EmployeeCollection(); this.employees.add(new Employee()); this.employee
public class Company{
private EmployeeCollection employees;
public Company(){
this.employees = new EmployeeCollection();
this.employees.add(new Employee());
this.employees.add(new Employee());
this.employees.add(new Employee());
this.employees.add(new Employee());
this.employees.add(new Employee());
}
public void MyMethod(){
Employee fourthEmployee = employees.getFourth();
}
}
public class EmployeeCollection extends ArrayList<Employee>{
public Employee getFourth(){
return this[3]; //<-- Error
}
public Employe getEmployee(int id){
for(int i = 0; i< this.size(); i++){ //<-- Error
if(id == this[i].id){ //<-- Error
return this[i]; //<-- Error
}
}
}
}
上市公司{
私人雇员收集雇员;
上市公司(){
this.employees=新员工集合();
this.employees.add(new employees());
this.employees.add(new employees());
this.employees.add(new employees());
this.employees.add(new employees());
this.employees.add(new employees());
}
公共方法(){
Employee-fourthEmployee=employees.getFourth();
}
}
公共类EmployeeCollection扩展了ArrayList{
公共雇员{
返回此[3];//您可以使用this
关键字,但问题是您在其上使用的是数组访问语法,这在Java中无效。请将其替换为调用get
方法
this.get(i)
ArrayList
的backingObject[]
是私有的,因此您不能继承它。如果可以,您可以像elementData[x]
一样引用它
只需调用this.get(x)
即可从数组中获取元素
但是,从设计的角度来看,最好创建一个包含ArrayList
的装饰器类,并以您需要的方式对其进行操作。列表不是数组,因此数组语法对它们不起作用。您可以使用this.get(3);
来代替。顺便说一句,您不应该在this.size()
上看到任何错误
this.get(i)