An object has a name attribute of type String and a dependency attribute of the same type of the object itself. Now if I create an instance of the object and set the same instance as the dependency attribute, then checking if the object is reflexive by comparing its name with the dependencies name does not work in the if statement.
class Job {
private String name;
private Job dependency;
Job(String name) {
this.name = name;
}
String getName() {
return name;
}
Job getDependency() {
return dependency;
}
void setDependency(Job dependency) {
this.dependency = dependency;
}
boolean hasDependency() {
return dependency != null;
}
}
class JobSequence {
private ArrayList<Job> jobsArrayList;
private ArrayList<Job> orderedJobsArrayList = new ArrayList<>();
JobSequence(ArrayList<Job> jobsArrayList) {
this.jobsArrayList = jobsArrayList;
}
void sortByDependency() {
for (Job job : jobsArrayList) {
if (!orderedJobsArrayList.contains(job)) orderedJobsArrayList.add(job);
if (job.hasDependency()) {
if (!isReflexive(job, job.getDependency())) {
if (!orderedJobsArrayList.contains(job.getDependency())) {
int index = orderedJobsArrayList.indexOf(job);
orderedJobsArrayList.set(index, job.getDependency());
orderedJobsArrayList.add(index + 1, job);
}
}
}
}
}
private boolean isReflexive(Job i, Job j) {
return i.getName().equals(j.getName());
}
public class Main {
public static void main(String[] args) {
Job a = new Job("a");
Job b = new Job("b");
Job c = new Job("c");
a.setDependency(null);
b.setDependency(null);
c.setDependency(c);
ArrayList<Job> jobArrayList = new ArrayList<>();
Collections.addAll(jobArrayList, a, b, c);
JobSequence sequence = new JobSequence(jobArrayList);
sequence.sortByDependency();
sequence.getOrderedJobsArrayList().forEach(p -> System.out.println(p.getName()));
}
}
Aucun commentaire:
Enregistrer un commentaire