I need help in getting an element of an ArrayList of one class and using it in another.
The task is basically allocating task entered in Job class which is placed in an arraylist in JobQueue class. The issue im having at the moment is that i have a duration as integers for each task within Job class and im trying to get a total duration utilised in JobQueue class if there is more than 1 task enetered.
Task:- get totalDuration of jobs in Job class to be used inside JobQueue class.
Here is what i have so far.
//first class that contains jobs created.
public class Job
{
//fields
private String jobName;
private int jobDuration;
private static final int DEFAULT_DURATION = 0;
public Job(String task, int duration)
{
//constructor used to create the job name and how long it will take to do one job (duration).
jobName = task;
if (duration > DEFAULT_DURATION)
{
jobDuration = duration;
}
else
{
jobDuration = DEFAULT_DURATION;
}
}
public String getName()
{
return jobName;
}
public int getDuration()
{
return jobDuration;
}
}
// 2nd class used to enter every job created into an Arraylist called myJobs.
public class JobQueue
{
private ArrayList <Job> myJobs;
private int totalDuration;
private static final int DEFAULT_NUM = 0;
public JobQueue()
{
myJobs = new ArrayList<Job>();
totalDuration = DEFAULT_NUM;
}
public ArrayList<Job> getPendingJobs()
{
return myJobs;
}
public void addJob(Job job)
{
myJobs.add(job);
}
}
//here i need a method that gets the total duration of jobs in the arraylist and returns total as an integer. Please help.
This would be your method, not much to it:
You also have a
totalDurationproperty that could be seen as a cached total duration value. This should be introduced only as a necessary evil, an optimization due to a noticed performance problem. If that is not your case, remove the property. If you really do need it, given your current API (jobs are only added), you could maintain the total value by changing youraddJobmethod:And then your required method to get the total duration would be just
However, as your code’s complexity grows, it usually becomes increasingly difficult to mantain the total duration invariant and there’s a breaking point where you must be very clear that you really need its speed advantage.