Question

In: Computer Science

3.2. Unfortunately, you cannot modify the Rectangle class so that it implements the Comparable interface. The...

3.2. Unfortunately, you cannot modify the Rectangle class so that it implements the Comparable interface. The Rectangle class is part of the standard library, and you cannot modify library classes.

Fortunately, there is a second sort method that you can use to sort a list of objects of any class, even if the class doesn't implement the Comparable interface.

Comparator<T> comp = . . .; 
   // for example, Comparator<Rectangle> comp = new RectangleComparator();
Collections.sort(list, comp); 

Comparator is an interface. Therefore, comp must be constructed as an object of some class that implements the Comparator interface.

What method(s) must that class implement? (: Look up the Comparator interface in the API documentation.)

Your answer :

Implement a Rectangle comparator

3.3. Implement a class RectangleComparator whose compare method compares two rectangles.

The method should return:

      a positive integer if the area of the first rectangle is larger than the area of the second rectangle

      a negative integer if the area of the first rectangle is smaller than the area of the second rectangle

      0 if the two rectangles have the same area

Part of the code has been provided for you below:

import java.util.Comparator;
import java.awt.Rectangle;
 
public class RectangleComparator implements Comparator<Rectangle>
{
   /**
      Compares two Rectangle objects.
      @param r1 the first rectangle
      @param r2 the second rectangle
      @return 1 if the area of the first rectangle is larger than the area of
            the second rectangle, -1 if the area of the first rectangle is
            smaller than the area of the second rectangle or 0 if the two
            rectangles have the same area
   */
   public int compare(Rectangle r1, Rectangle r2)
   {
      . . .
   }  
}

Your answer :

 
 

Testing the rectangle comparator

3.4. Write a test program that adds the three rectangles below to a list, constructs a rectangle comparator, sorts the list, and prints the sorted list and the expected values.

   Rectangle rect1 = new Rectangle(5, 10, 20, 30); 
   Rectangle rect2 = new Rectangle(10, 20, 30, 15); 
   Rectangle rect3 = new Rectangle(20, 30, 45, 10);  

What is your test program?

Your answer :

 

Solutions

Expert Solution

Thanks for the question, Here are the 2 parts.

=========================================================================

import java.util.Comparator;
import java.awt.Rectangle;

public class RectangleComparator implements Comparator<Rectangle> {


    public int compare(Rectangle o1, Rectangle o2) {
        if (o1.getWidth() * o1.getHeight() - o2.getWidth() * o2.getHeight() > 0) return 1;
        else if (o1.getWidth() * o1.getHeight() - o2.getWidth() * o2.getHeight() < 0) return -1;
        else return 0;
    }
}

=============================================================

public class TestProgram {

    public static void main(String[] args) {

        Rectangle rect1 = new Rectangle(5, 10, 20, 30);
        Rectangle rect2 = new Rectangle(10, 20, 30, 15);
        Rectangle rect3 = new Rectangle(20, 30, 45, 10);

        Rectangle[] rectangles = new Rectangle[3];
        rectangles[0] = rect1;
        rectangles[1] = rect2;
        rectangles[2] = rect3;

        System.out.println("Before Sorting: ");
        for (Rectangle r : rectangles) System.out.println(r + ", [Area: " + r.getHeight() * r.getWidth() + "]");
        Arrays.sort(rectangles, new RectangleComparator());
        System.out.println("After Sorting: ");
        for (Rectangle r : rectangles) System.out.println(r + ", [Area: " + r.getHeight() * r.getWidth() + "]");


    }
}

=============================================================


Related Solutions

4) Define an abstract class Name Java class that implements interface Comparable   
4) Define an abstract class Name Java class that implements interface Comparable   
In Java: Job class The Job implements the Comparable interface A Job object is instantiated with...
In Java: Job class The Job implements the Comparable interface A Job object is instantiated with three int variables, indicating the arrivalTime, the timeForTheJob, and the priority. When the Job is created it is given the next sequential ID starting from 1. (You should use a static variable to keep track of where you are in ID assignment.) There are also int variables for startTime, waitTime (in queue) and endTime for the Job. The following methods are required: getID, set...
In Java: Job class The Job implements the Comparable interface A Job object is instantiated with...
In Java: Job class The Job implements the Comparable interface A Job object is instantiated with three int variables, indicating the arrivalTime, the timeForTheJob, and the priority. When the Job is created it is given the next sequential ID starting from 1. (You should use a static variable to keep track of where you are in ID assignment.) There are also int variables for startTime, waitTime (in queue) and endTime for the Job. The following methods are required: getID, set...
(Enable Rectangle comparable) Rewrite the Rectangle class in Listing 13.3 to extend GeometricObject and implement the...
(Enable Rectangle comparable) Rewrite the Rectangle class in Listing 13.3 to extend GeometricObject and implement the Comparable interface. Override the equals method in the Object class. Two Rectangle objects are equal if their areas are the same. Draw the UML diagram that involves Rectangle, GeometricObject, and Comparable. Also include explain paragraph.
data structure class: a. syntax for generics b. comparable interface c.how do you implement interface answer...
data structure class: a. syntax for generics b. comparable interface c.how do you implement interface answer for all of them please. answer for all of them please
If a class A implements interface I1 and class C and D are derived from class...
If a class A implements interface I1 and class C and D are derived from class A, a variable of type I1 can be used to hold references of what type of objects? which one is correct 1. A, C, and D 2. A and D
In this class add Comparable interface. In the driver program create a few objects and In...
In this class add Comparable interface. In the driver program create a few objects and In the driver program create a few objects and compare them . then create a list of those objects and sort them .A Quadratic is bigger than another Quadratic if it opens faster package pack2; /** * This is a program for defining a quadratic equation * @author sonik */ public class Quadratic { public int coeffX2 = 0; public int coeffX = 0; public...
Define a class of queues that implements the interface QueueInterface, as defined in Listing 7-1 in...
Define a class of queues that implements the interface QueueInterface, as defined in Listing 7-1 in Chapter 7. Use an instance of the class ArrayList to contain a queues entries. Then write a driver/test program adequately demonstrates your new class. Note that you might have to handle exceptions thrown by methods of ArrayList. Deliverables: EmptyQueueException.java (given in Lab_7_StartUp folder) QueueInterface.java (given in Lab_7_StartUp folder) ArrayListQueue.java (need to create) Lab7.java (need to create) QueInterface: @author Frank M. Carrano @author Timothy M....
In java design and code a class named comparableTriangle that extends Triangle and implements Comparable. Implement...
In java design and code a class named comparableTriangle that extends Triangle and implements Comparable. Implement the compareTo method to compare the triangles on the basis of similarity. Draw the UML diagram for your classes. Write a Driver class (class which instantiates the comparableTriangle objects) to determine if two instances of ComparableTriangle objects are similar (sample output below). It should prompt the user to enter the 3 sides of each triangle and then display whether or not the are similar...
Write a class "LinkedBag" which implements this interface. The LinkedBag class has two instance variables firstNode...
Write a class "LinkedBag" which implements this interface. The LinkedBag class has two instance variables firstNode and numberOfEntries. It has an inner class Node. BagInterface.java /** An interface that describes the operations of a bag of objects. @author Frank M. Carrano @author Timothy M. Henry @version 4.1*/public interface BagInterface<T>{ /** Gets the current number of entries in this bag. @return The integer number of entries currently in the bag. */ public int getCurrentSize(); /** Sees whether this bag is empty....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT