Making EOs implement Comparable
Making EOs implement Comparable
- Subject: Making EOs implement Comparable
- From: Florijan Stamenkovic <email@hidden>
- Date: Wed, 19 Mar 2008 13:18:43 -0400
Hi all,
In my apps I could benefit from EOs implementing Comparable, to be
able to use to-one relationships in in-memory sorting and qualifying.
Has anyone ever implemented the compareTo(...) method for EOs so that
it is absolutely consistent with equals?
My attempt is below, if you want to check it for making sense. It is
JBND based, so the comparison is based on the DataObject interface.
DataObjects can be EOs, non EOF in memory data caches (used for
deferred editing and adding), and a few other key-value based data
holders used in JBND.
public int compareTo(DataObject object){
if(object.equals(this)) return 0;
// DataType check, getDataType().name() is the same as entityName()
// for non JBND specific DataTypes
int rVal = NamingSupport.typeName(getDataType().name()).compareTo(
NamingSupport.typeName(object.getDataType().name()));
if(rVal != 0) return rVal;
// DataObject implementation check
if(!getClass().equals(object.getClass())){
rVal = getClass().getName().compareTo(object.getClass().getName());
if(rVal != 0) return rVal;
}
// see if one is saved and the other one is not
if(this.isPersistent() && !object.isPersistent())
return -100;
if(!this.isPersistent() && object.isPersistent())
return 100;
// do a toString comparison
String thisS = this.toString();
String thatS = object.toString();
rVal = thisS != null && thatS != null ? thisS.compareTo(thatS) : 0;
if(rVal != 0) return rVal;
// do attribute per attribute comparison
String[] attributes = getDataType().attributes();
for(String attribute : attributes){
Object a1 = get(attribute), a2 = object.get(attribute);
if(a1 != null && a2 != null && a1 instanceof Comparable){
rVal = ((Comparable)a1).compareTo(a2);
if(rVal != 0) return rVal;
}
}
// this is just bad, comparing attributes still yields nothing
rVal = hashCode() - object.hashCode();
if(rVal != 0) return rVal;
rVal = System.identityHashCode(this) - System.identityHashCode
(object);
if(rVal != 0) return rVal;
// there's virtually nothing left to compare on!
return 0;
}
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Webobjects-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden