Compare two objects with "<" or ">" operators in Java -
how make 2 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) something.
i've made myobject class header as
public class myobject<t extends comparable<t>> implements comparable<myobject<t>>
, created method comp gain got can use "sort" on list of objects, how can compare 2 objects each other directly?
if(obj1.compareto(obj2) > 0)
the way?
you cannot operator overloading in java. means not able define custom behaviors operators such +
, >
, <
, ==
, etc. in own classes.
as noted, implementing comparable
, using compareto()
method way go in case.
another option create comparator
(see docs), specially if doesn't make sense class implement comparable
or if need compare objects same class in different ways.
to improve code readability use compareto()
custom methods may more natural. example:
boolean isgreaterthan(myobject<t> that) { return this.compareto(that) > 0; } boolean islessthan(myobject<t> that) { return this.compareto(that) < 0; }
then use them this:
if (obj1.isgreaterthan(obj2)) { // }
Comments
Post a Comment