Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA Need help with compareTo method public class Interval implements Comparable

ID: 3863443 • Letter: J

Question

JAVA

Need help with compareTo method

public class Interval implements Comparable<Interval> {
   private final int begin;
   private final int end;
  
   public Interval(int begin, int end) {
       this.begin = begin;
       this.end = end;
   }
  
   // compare first by begin time, then by end time; see the examples below:
   // (3, 7) < (4, 5) < (4, 6)
public int compareTo(Interval o) {
       return 0
;
   }
  
   public String toString() {
       return "(" + begin + "," + end + ")";
   }
}

Explanation / Answer

public class Interval implements Comparable { private final int begin; private final int end; public Interval(int begin, int end) { this.begin = begin; this.end = end; } // compare first by begin time, then by end time; see the examples below: // (3, 7) < (4, 5) < (4, 6) public int compareTo(Interval o) { if(this.begin>o.begin||(this.begin==o.begin && this.end>o.end) ){ return 1; } else if(this.begin==o.begin&&this.end==o.end){ return 0; } else { return -1; } } public String toString() { return "(" + begin + "," + end + ")"; } }