How to add a field to an ArrayList from a differen

2019-10-02 08:19发布

I'm quite new to programming, I'm building a program that adds different jobs done by the same person in an organisation to an ArrayList.

I'm trying to add more than two job titles from the main class to the ArrayList but I keep getting an error, could you please guide me in the right direction?

import java.util.ArrayList;                                                 
public class Employee
{
 private String name;
  private String department;


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

 public void setJob(ArrayList<String> job)
  {
  this.job =job;
 }  

 public ArrayList<String> getJob()
 {
   return job;
 }  
 }

Here is the Main class
public class Main

{
 public static void main(String[] args)
 {

  Employee walter = new Employee();
   walter.setName("Walter White");
   walter.setJob("Chemistry Teacher");//The error occurs here it says 
   //method setJob in class Employee cannot be applied to given types;

walter.setJob("Chemistry Teacher"); ^ required: java.util.ArrayList found: java.lang.String reason: actual argument java.lang.String cannot be converted to java.util.ArrayList by method invocation conversion

   walter.setDepartment("Science");
  }
  }

标签: java
1条回答
唯我独甜
2楼-- · 2019-10-02 09:01

You defined job as an ArrayList of String, therefore you can't set it with a plain String you must pass a List to it. Here is one way to do it:

walter.setJob(Arrays.asList(new String("Chemistry Teacher")));

Or less verbal way as suggested by @Daedalus

walter.setJob(Arrays.asList("Chemistry Teacher"));

If your requirement is that an employee have many jobs than there is nothing wrong with defining it as a list. The more elegant way would be to follow the suggestion of @HovercraftFullOfEels in comments above but since you are a starter you should know that it is not wrong per se.

His suggestion is that you have a method to add a job to the existing list so:

public void addJob(String jobName){
    job.add(jobName);
}

Then you would use:

 walter.addJob("Chemistry Teacher");
查看更多
登录 后发表回答