Reputation: 23
I have two classes, let's say DerivedOne and DerivedTwo, derived from a base class Base.
Assuming I have these:
DerivedOne d1;
DerivedTwo d2;
when I compare d1 and d2, I'd like d1 to always be smaller, in other words an object of DerivedOne should have a higher priority than an object of DerivedTwo. What is the best/nicest way to do that?
Upvotes: 2
Views: 603
Reputation: 4228
Make both objects implements Comparable<Derivedparent>
interface
(or parent implements and subclass override) and then in the CompareTo method put something like this:
public class DerivedOne{
public int compareTo(DerivedParent dp){
if (dp.instanceOf(DerivedTwo){
return -1;
}
//More comparisons
}
}
public class DerivedTwo{
public int compareTo(DerivedParent dp){
if (dp.instanceOf(DerivedOne){
return 1;
}
//More comparisons
}
}
Upvotes: 2
Reputation: 10039
Most probably a proper implementation of java.util.Comparator<YourSuperClass>
Upvotes: 2
Reputation: 13465
In the super class declare a variable as priority.
And in the subclasses constructor, initialize that.
class A
{
int priority;
}
class Derived1
{
Derived1()
{
priority=1;
}
}
class Derived2
{
Derived2()
{
priority=0;
}
}
Upvotes: 2
Reputation: 3946
I do not know if this is the nicest, but I would recommend using the instanceof
operator inside the comparator.
Upvotes: 4