Reputation: 930
I know that this class compares two objects in a class(e.g. two Strings), but what types aren't comparable using this class?
Upvotes: 2
Views: 1036
Reputation: 1315
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();
}
}
Upvotes: 3
Reputation: 37950
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.
Upvotes: 15