I know I can call Collections.sort() on an ArrayList in Java, but I am currently trying to overload a constructor, and in the second one I would like to call the first constructor. However, I want to pass a sorted list as one of the arguments, but Java won't let me call this() after sorting the list - it requires this() to be the first line. I could just put Collections.sort(myList) in the constructor, but I don't know if this method returns the sorted list, but ideally I would like to return the sorted list without mutating the original.
Here is my code (for a period such as you would find in a school or university), including the error:
public class Period {
private String name;
private LocalDateTime start;
// duration in seconds
private int duration;
private Lecturer lecturer;
private ArrayList<Demonstrator> dems;
private ArrayList<Skill> skills;
public Period(String name, LocalDateTime start, int duration, Lecturer lecturer) {
this.name = name;
this.start = start;
this.duration = duration;
this.lecturer = lecturer;
this.dems = new ArrayList<>();
this.skills = new ArrayList<>();
}
public Period(String name, ArrayList<AvailBlock> blocks, Lecturer lecturer) {
// this line is illegal, but shows you what I'm trying to do.
Collections.sort(blocks);
this(name, blocks.get(0).getStart(), ( blocks.size() * AvailBlock.LENGTH ), lecturer);
}
...
}
The AvailBlock class has a start time as a LocalDateTime object, and a fixed duration (currently 15 minutes). I am trying to have the option of creating a period with a duration in seconds, or just passing in a list of AvailBlock objects and letting it figure out when the period starts and how long it should be.
Here is the beginning of the AvailBlock class:
public class AvailBlock implements Comparable {
// the start time of the slot
private LocalDateTime start;
// Length of slots in seconds
public static final int LENGTH = 900;
public AvailBlock(LocalDateTime start) {
this.start = start;
}
...
}