Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在集合类中使用此选项_Java_List_Collections_This - Fatal编程技术网

Java 如何在集合类中使用此选项

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

如何使用此关键字引用从ArrayList继承的类中的集合,如下所示。我在设计时出错,IDE不允许我编译代码

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
的backing
Object[]
是私有的,因此您不能继承它。如果可以,您可以像
elementData[x]
一样引用它

只需调用
this.get(x)
即可从数组中获取元素


但是,从设计的角度来看,最好创建一个包含
ArrayList
的装饰器类,并以您需要的方式对其进行操作。

列表不是数组,因此数组语法对它们不起作用。您可以使用
this.get(3);
来代替。顺便说一句,您不应该在
this.size()
上看到任何错误
this.get(i)