Question

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 Improve this question Transcribed image text
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 Coins

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...

  • What is a Java interface? It is a __________ ? base class derived class set of...

    What is a Java interface? It is a __________ ? base class derived class set of instance variables specification of required methods, including method names, signatures, and return values What is the required method of the Comparable interface? comparator compare compareTo spaceship What is the load factor for a HashMap collection? It is the maximum ___________ of the HashMap collection. capacity number of empty cells percentage of empty cells percentage of occupied cells Which choice defined a HashMap with integer...

  • Objectives: GUI Tasks: In Lab 4, you have completed a typical function of music player --...

    Objectives: GUI Tasks: In Lab 4, you have completed a typical function of music player -- sorting song lists. In this assignment, you are asked to design a graphic user interface (GUI) for this function. To start, create a Java project named CS235A4_YourName. Then, copy the class Singer and class Song from finished Lab 4 and paste into the created project (src folder). Define another class TestSongGUI to implement a GUI application of sorting songs. Your application must provide the...

  • Please create two tests classes for the code down below that use all of the methods...

    Please create two tests classes for the code down below that use all of the methods in the Transaction class, and all of the non-inherited methods in the derived class. Overridden methods must be tested again for the derived classes. The first test class should be a traditional test class named "Test1" while the second test class should be a JUnit test class named "Test2". All I need is to test the classes, thanks! Use a package that contains 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...

  • in java Define a class named ComparableNames thats extends Person and implements comparable Define a class...

    in java Define a class named ComparableNames thats extends Person and implements comparable Define a class named ComparableNames that extends Person (defined below) and implements Comparable. Override the compare To method to compare the person on the basis of name. Write a test class to find the order of two ComparableNames. class Person String name; Person00 Person(String n) name=n: Hint: in class ComparableName, you only need a constructor with arg to initialize the data filed defined in the super class...

  • 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 */...

  • Adapt your Rational class : public class Rational { private int num; private int denom; public...

    Adapt your Rational class : public class Rational { private int num; private int denom; public Rational() { num = 0; denom = 1; } public Rational(int num, int denom) { this.num = num; this.denom = denom; } int getNum() { return num; } int getDenom() { return denom; } public Rational add(Rational rhs) { return new Rational(num * rhs.denom + rhs.num * denom, denom * rhs.denom); } public Rational subtract(Rational rhs) { return new Rational(num * rhs.denom - rhs.num...

  • public class Car {    /* four private instance variables*/        private String make;   ...

    public class Car {    /* four private instance variables*/        private String make;        private String model;        private int mileage ;        private int year;        //        /* four argument constructor for the instance variables.*/        public Car(String make) {            super();        }        public Car(String make, String model, int year, int mileage) {        super();        this.make = make;        this.model...

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

     Given main(). define the Artist class (in file Artist java) with constructors to initialize an artist's information, get methods, and a printlnfo() method. The default constructor should initialize the artist's name to "None' and the years of birth and death to 0. printinfo() should display Artist Name, born XXXX if the year of death is -1 or Artist Name (XXXX-YYYY) otherwise. Define the Artwork class (in file Artwork.java) with constructors to initialize an artwork's information, get methods, and a printinfo() method. The constructor should...

ADVERTISEMENT
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.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT