我想实现比较 object1 和 object2 的 Comparator,其中这两个对象是复杂对象(嵌套对象)。
我的要求是,如果 object2 中有任何 null 值,并且 object1 中的相应值为 null 或不为 null,那么我的比较器应该返回 true,但是如果 object2 中的值不为 null 并且对象 1 中的相应值不同或 null 那么它应该返回错误的。
这些值可能是对象内对象等等或基础对象。
你能建议我如何实现 compareTo() 方法,以便得到我想要的结果。
compareTo 方法通常不返回 true 或 false 比较器工作:如果第一个给定对象小于第二个给定对象,则返回 -1 如果第一个给定对象大于第二个给定对象,则返回 1,如果物体是均匀的
这将类似于(考虑到您想根据其中的字符串比较两个对象):
if (a.getString() == null && a.getString() == null) {
return 0; //both of them are null: return equal
}
if (a.getString() == null) {
return 1; //first one is null: second is bigger
}
if (b.getString() == null) {
return -1; //second one is null: first is bigger
}
return a.getString().compareTo(b.getString()); //compare the two strings
//inside, with the already
//existing method from the
//String class
考虑到您没有给出任何代码示例,此代码将符合您的需求