Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What isn't comparable by the Comparable class?

Tags:

java

I know that this class compares two objects in a class(e.g. two Strings), but what types aren't comparable using this class?

like image 690
Clint Avatar asked Feb 13 '26 01:02

Clint


2 Answers

That's not quite how it works. Comparable is an interface that any class may choose to implement in order to indicate that instances of the class may be compared using the class' compareTo() method. So you can choose to implement this interface in any class you create yourself (however, you must write the code for compareTo() yourself, since Java doesn't know how to compare your objects in a meaningful manner).

Some built-in classes implement Comparable and others don't - there might be a list somewhere, but it would be way too long for an SO answer. If you are wondering about whether a specific class implements compareTo(), check its documentation (and see if the comparison does what you expect) or simply try to call that method. If there is a built-in or third-party class that does not implement Comparable, you need to create a Comparator instead in order to compare them.

A Comparator may compare anything you wish, because you are the one who decides how it should work.

like image 191
Aasmund Eldhuset Avatar answered Feb 14 '26 15:02

Aasmund Eldhuset


Actually, you can compare everything in Java.

For instance, you have a class X, which is incomparable. You can make this class an attribute to another class C and make C comparable, override its compareTo() method.

For example, it doesn't make sense to compare Colors

This is right. Even though it doesn't make sense, you can. Here is the answer for the question:

Which color is brighter?

public class ComparableColor implements Comparable<ComparableColor> 
{
    Color color;
    public ComparableColor(Color color)
    {
        this.color = color;
    }
    @Override
    public int compareTo(ComparableColor c) 
    {
        return c.color.getAlpha() - this.color.getAlpha();

    }

}
like image 29
padawan Avatar answered Feb 14 '26 14:02

padawan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!