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

How do I implement a comparator by creating an anonymous inner class that orders

ID: 3754388 • Letter: H

Question

How do I implement a comparator by creating an anonymous inner class that orders objects by their length with type Duration? I have my length converted to minutes.

I have this

private final String title;

private final Duration length;

   public Video(String title, Duration length) {

       this.title = title;

  this.length = length;

}

public String title() {

       return this.title;

   }

   public long minutes() {

       return this.length.toMinutes();

   }

   @Override

   public String toString() {

       DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);

       String stringFormat = ""%s", %d minutes long";

       Object[] args = {

               this.title,

  this.minutes(),

};

       return String.format(stringFormat, args);

   }

// @see Duration#compareTo(Duration)

public static final Comparator<Video> LENGTH_ORDER = ...;

}

Explanation / Answer

Acutally comprator is used to sort the objects in list, so you can not write the comparator here,

you can write comprator in another method where you have the the list of Video object now you want sort based on that length, than you can use comparator

if you want write with in the class than comparable suits your requirement . I am giving you with the comprable interface

package sep24.test;

package sep24.test;

public class Video implements Comparable {

private final String title;

private final Duration length;

public Video(String title, Duration length) {

this.title = title;

this.length = length;

}

public String title() {

return this.title;

}

public long minutes() {

return this.length.toMinutes();

}

@Override

public String toString() {

DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);

String stringFormat = ""%s", %d minutes long";

Object[] args = {

this.title,

this.minutes(),

};

return String.format(stringFormat, args);

}

@Override

public int compareTo(Object aO) {

Video v =(Video)aO;

Long i1 = new Long(this.minutes());

Long i2 = new Long(v.minutes());

return i1.compareTo(i2);

}

// @see Duration#compareTo(Duration)

}

}

Note: Feel free to comment if you have any questions

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote