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");
}
}
You defined
job
as anArrayList
ofString
, therefore you can't set it with a plain String you must pass a List to it. Here is one way to do it:Or less verbal way as suggested by @Daedalus
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:
Then you would use: