Homework Help Question & Answers

JAVA The Comparable interface is defined as follows: public interface Comparable<T> {         int compareTo(T other);...

JAVA

The Comparable interface is defined as follows:

public interface Comparable<T> {

        int compareTo(T other);

}

A Film class is defined as

public class Film {

     private String title;

     private int yearOfRelease;

    

     public Film(String title, int yearOfRelease) {

          super();

          this.title = title;

          this.yearOfRelease = yearOfRelease;

     }

    

     public void display()

     {

System.out.println("Title " + title +". Release" + yearOfRelease);

     }

}

Rewrite the Film class so that it implements the Comparable interface that would cause films to be sorted by year of release and in the event that the year is the same then it would sort by title. Implement an equals method that overrides the equals method in the Object class to test for equality in the Film class. A song is said to be equal if the year and the title are equal.

0 0
Add a comment
Answer #1

Hello, I have a solution for you. Implemented everything as per the requirements. Defined following things in this answer.

  1. Modified the class Film.java to implement Comparable interface, and implemented the function compareTo() to compare two Film objects by release year (descending order), and in case of equal years, by title (alphabetical order).
  2. Overridden the equals() method as per the needs.
  3. Created a Test class, defined an ArrayList of Film objects, created a few Film objects, added it to the list, and then sorted it. Finally displayed the sorted list.
  4. Comments are included, If you have any doubts, feel free to ask, Thanks

//Film.java

public class Film implements Comparable<Film> {

      private String title;

      private int yearOfRelease;

      public Film(String title, int yearOfRelease) {

            super();

            this.title = title;

            this.yearOfRelease = yearOfRelease;

      }

      public void display() {

            System.out.println("Title: " + title + ", Release: " + yearOfRelease);

      }

      /**

      * method to compare two Film objects for sorting. Will help to sort by

      * descending order of release year, if the year is same, sorts by the title

      * (alphabetically)

      */

      public int compareTo(Film other) {

            if (this.yearOfRelease > other.yearOfRelease) {

                  return -1;

            } else if (this.yearOfRelease < other.yearOfRelease) {

                  return 1;

            } else {

                  /**

                  * year of release is the same, so comparing titles

                  */

                  return this.title.compareTo(other.title);

            }

      }

      /**

      * method to check if two objects are equal (only if title and release year

      * are same for both Film objects

      */

      @Override

      public boolean equals(Object o) {

            /**

            * Checking if the object passed in the argument is a Film object

            */

            if (o instanceof Film) {

                  /**

                  * Type Casting

                  */

                  Film f = (Film) o;

                  if (this.title.equals(f.title)

                              && this.yearOfRelease == f.yearOfRelease) {

                        /**

                        * both titles are same, and both release years are same

                        */

                        return true;

                  }

            }

            return false;

      }

}

//Test.java

import java.util.ArrayList;

import java.util.Collections;

public class Test {

      public static void main(String[] args) {

            /**

            * Defining an ArrayList of Film

            */

            ArrayList<Film> filmsList=new ArrayList<Film>();

            /**

            * Creating a few Film objects

            */

            Film film1=new Film("Hello", 2000);

            Film film2=new Film("Wonder Woman", 2016);

            Film film3=new Film("Space Odeyssey", 1968);

            Film film4=new Film("Matrix", 1999);

            Film film5=new Film("Matrix Reloaded", 2010);

            Film film6=new Film("Avengers 2", 2016);

           

            /**

            * Adding films to the arraylist

            */

            filmsList.add(film1);

            filmsList.add(film2);

            filmsList.add(film3);

            filmsList.add(film4);

            filmsList.add(film5);

            filmsList.add(film6);

            /**

            * Sorting

            */

            Collections.sort(filmsList);

            /**

            * Displaying

            */

            for(Film f:filmsList){

                  f.display();

            }

      }

}

/*OUTPUT*/

Title: Avengers 2, Release: 2016

Title: Wonder Woman, Release: 2016

Title: Matrix Reloaded, Release: 2010

Title: Hello, Release: 2000

Title: Matrix, Release: 1999

Title: Space Odeyssey, Release: 1968

Add a comment
Know the answer?
Add Answer to:
JAVA The Comparable interface is defined as follows: public interface Comparable<T> {         int compareTo(T other);...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coin

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Implement the classes in the following class diagram. The Book class implements the Comparable interface. Use impl...

    Implement the classes in the following class diagram. The Book class implements the Comparable interface. Use implements Comparable<Book> in the class definition. Now, all book objects are instances of the java.lang.Comparable interface. Write a test program that creates an array of ten books. 1. Use Arrays.sort( Book[]l books) from the java.util package to sort the array. The order of objects in the array is determined using compareTo...) method. 2. Write a method that returns the most expensive book in the...

  • Rewrite the Course class in Listing 10.6 to implement the comparable and the cloneable interfaces. The...

    Rewrite the Course class in Listing 10.6 to implement the comparable and the cloneable interfaces. The clone method must allow a deep copy on the students field. In addition, add the equals(Object o) and the toString() methods. Write a test program to invoke the compareTo, clone, equals, and toString methods in a meaningful way. Below is the Listing from the book that needs to be rewritten public class Course {    private String courseName;    private String[] students = new...

  • Create a program called GeneralizedBubbleSort that will make use of the Comparable Interface in the same...

    Create a program called GeneralizedBubbleSort that will make use of the Comparable Interface in the same way it is used in the GeneralizedSelectionSort. You should use the attached ComparableDemo to test your program. public class ComparableDemo { public static void main(String[] args) { Double[] d = new Double[10]; for (int i = 0; i < d.length; i++) d[i] = new Double(d.length - i); System.out.println("Before sorting:"); int i; for (i = 0; i < d.length; i++) System.out.print(d[i].doubleValue( ) + ", ");...

  • For Java please. Artwork. java import java.util.Scanner; public class ArtworkLabel { public static void main(String[] args)...

    For Java please. Artwork. java import java.util.Scanner; public class ArtworkLabel { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); String userTitle, userArtistName; int yearCreated, userBirthYear, userDeathYear; userArtistName = scnr.nextLine(); userBirthYear = scnr.nextInt(); scnr.nextLine(); userDeathYear = scnr.nextInt(); scnr.nextLine(); userTitle = scnr.nextLine(); yearCreated = scnr.nextInt(); Artist userArtist = new Artist(userArtistName, userBirthYear, userDeathYear); Artwork newArtwork = new Artwork(userTitle, yearCreated, userArtist); newArtwork.printInfo(); } } ------------------------------------------------------------------------------ Artist.java public class Artist { // TODO: Declare private fields - artistName, birthYear, deathYear // TODO:...

  • Can someone please help me with this JAVA problem about Abstract classes and Interfaces? They are...

    Can someone please help me with this JAVA problem about Abstract classes and Interfaces? They are asking me to explain how the following class SortRectangle works. What is the output of the problem? The program is: public class SortRectangles { public static void main(String[] args) { new ComparableRectangle(3.4, 5.4); new ComparableRectangle(13.24, 55.4); new ComparableRectangle(7.4, 35.4); new ComparableRectangle(1.4, 25.4); java.util.Arrays.sort(rectangles); for (Rectangle rectangle: rectangles){ System.out.print(rectangle + " "); System.out.println(); } }    } ============================================================================= public class ComparableRectangle extends Rectangle implements Comparable<ComparableRectangle>{...

  • public class Song { private String title; private String artist; private int duration; public Song() {...

    public class Song { private String title; private String artist; private int duration; public Song() { this("", "", 0, 0); } public Song(String t, String a, int m, int s) { title = t; artist = a; duration = m * 60 + s; } public String getTitle() { return title; } public String getArtist() { return artist; } public int getDuration() { return duration; } public int getMinutes() { return duration / 60; } public int getSeconds() { return...

  • Homework Help Movie Class Java

    Create a class named Movie that can be used with your video rental business. The Movie class should track the Motion Picture Association of America (MPAA) rating(e.g., Rated G, PG-13, R), ID Number, and movie title with appropriate accessor and mutator methods. Also create and equals() method that overrides Object's equals()method, where two movies are equal if their ID number is identical.Next, create three additional movie classes named Action, Comedy, and Drama that are derived from Movie. Finally, create an...

  • Colorable interface program confusion

    I've been tinkering with this for a little bit now, I'm not sure why but I'm drawing a blank. Could someone please assist me in any way.The program:Design an interface named Colorable with a void method named howToColor(). Every class of a colorable object must implement the Colorable interface. Design a classnamed Square that extends GeometricObject and implements Colorable. Implement howToColor to display a message "Color all four sides"Write a test program that creates an array of five GeometricObjects. For...

  • public class Item implements Comparable { private String name; private double price; /** * Constructor for...

    public class Item implements Comparable { private String name; private double price; /** * Constructor for objects of class Item * @param theName name of item * @param thePrice price of item */ public Item(String theName, double thePrice) { name = theName; price = thePrice; }    /** * gets the name * @return name name of item */ public String getName() { return name; }    /** * gets price of item * @return price price of item */...

  • Help finishing up this program in Java

    This needs to be done in Java and some of the code is attached at the bottom. I need help with additional methods/constructors being added to what I already have. Itwill be a life savor is someone can help me out with this!In Addition add and use the following:All appropriate accessor and mutator methods(getters and setters)An Equals methodA toString methoda default (no argument) constructorAn overloaded constructorA copy constructora clone methoda finilize methoda dispose methodOriginal ProjectCreate a class named Movie that...

Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.