简体   繁体   English

类java中的ArrayList获取器和设置器

[英]ArrayList getter and setter in a class java

public class Employee                                               
{
private String name;
private String department;


private ArrayList<Employee>job= new ArrayList();

// just want to add getter and setter for this ArrayList //只想为此ArrayList添加getter和setter

public void setJob(Employee j)
{
job.add(j);

// this is my setter //这是我的二传手

I want to be able to add later on as many 'job' as I want by extending the arraylist 我希望以后可以通过扩展arraylist尽可能多地添加“作业”

While you can have setters and getter of List type, you should think carefully about their implementation, because most lists are mutable. 尽管可以使用List类型的setter和getter,但是您应该仔细考虑它们的实现,因为大多数列表都是可变的。 For instance, assume that you want to validate that the jobs list is not empty. 例如,假设您要验证jobs列表不为空。

public void setJob(List<Employee> jobs) {
  if (jobs.isEmpty()) throw new RuntimeException();
  this.job = jobs;
}

Now the following code produces an employee without jobs: 现在,以下代码产生了一个没有工作的雇员:

Employee e = ...;
e.setJobs(jobs);
jobs.clear();
//the employee now has no jobs :-(

You can avoid this issue by making a defensive copy 您可以通过制作防御性副本来避免此问题

public void setJob(List<Employee> j) {
  this.job = new ArrayList<>(j);
}

The same applies to the getter. 吸气剂也是如此。 If you implement it as: 如果将其实现为:

public List<Employee> getJobs() {
   return this.jobs;
}

you are allowing the caller to modify the private job list without invoking the corresponding setter: myEmployee.getJobs().clear() . 您允许调用者修改私有作业列表而无需调用相应的setter: myEmployee.getJobs().clear()

In this case, you may return an unmodifiable list instead of returning the inner object. 在这种情况下,您可以返回不可修改的列表,而不是返回内部对象。

public List<Employee> getJobs() {
   return java.util.Collections.unmodifiableList(this.jobs);
}    

通常对于集合或数组,您将使用addJob,removeJob和getJobs而不是获取/设置对。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM