Question

Using java language Assume you have a graphical user interface with a bunch of Rectangles that...

Using java language

Assume you have a graphical user interface with a bunch of Rectangles that you added

randomly all over the screen, and saved in an ArrayList<Rectangle> called

rectangles. The built-in Rectangle shape class is not implemented to be Comparable,

but you want to be able to sort the rectangles in order of how they appear in the interface from

left to right. If two Rectangles align on the left, the Rectangle up higher in the interface should

come first. Note: the built-in Rectangle class has methods getX(), getY(),

getWidth(), and getHeight(), all of which return a double. Write your own comparator

so that you can use the following line to sort your Rectangles:

Collections.sort(rectangles, new MyRectangleComparator());

----------------------------------------------------------------

import java.util.Comparator;

public class MyRectangleComparator

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.Comparator;

public class MyRectangleComparator implements Comparator<Rectangle> {

    @Override
    public int compare(Rectangle rectangle1, Rectangle rectangle2) {
        if (rectangle1.getX() == rectangle2.getX()) {
            return Double.compare(rectangle1.getY(), rectangle2.getY());
        }
        return Double.compare(rectangle1.getX(), rectangle2.getX());
    }
}
Add a comment
Know the answer?
Add Answer to:
Using java language Assume you have a graphical user interface with a bunch of Rectangles that...
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
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