How to make two objects in Java comparable using "<" or ">" e.g.
MyObject<String> obj1= new MyObject<String>(“blablabla”, 25);
MyObject<String> obj2= new MyObject<String>(“nannaanana”, 17);
if (obj1 > obj2)
do something.
I've made MyObject class header as
public class MyObject<T extends Comparable<T>> implements Comparable<MyObject<T>>
and created method Comp but all the gain I got is now I can use "sort" on the list of objects, but how can I compare two objects to each other directly? Is
if(obj1.compareTo(obj2) > 0)
do something
the only way?
compareTo
] the only way?" Yep. – Luster<
or>
operators in Java. – Aristaeus>
&<
because there might exist more than one variable in your object and Java won't know which variable you want to use for comparison. If you do not override the compareTo method, it will compare the string object in lexical order. – ThackeraycompareTo
isn't the only way--you could defineisLessThan
,isGreaterThan
, etc. methods if you want, that returnboolean
. It's arguable that they'd be more readable thancompareTo
. – Squalid