Java比较器逻辑。关于更好的写作方法的建议

Java比较器逻辑。关于更好的写作方法的建议,java,comparator,Java,Comparator,下面是我为CustomComparator编写的一段逻辑,但不是很满意。有谁能给我一些建议,告诉我如何改进它 public class CustomComparator implements Comparator<Offer>, Serializable { private static final long serialVersionUID = 8040322980719271561L; @Override public int compare(final Offer o1,

下面是我为CustomComparator编写的一段逻辑,但不是很满意。有谁能给我一些建议,告诉我如何改进它

public class CustomComparator implements Comparator<Offer>, Serializable {

private static final long serialVersionUID = 8040322980719271561L;

@Override
public int compare(final Offer o1, final Offer o2) {

    int comparisonIndicator = 0;

    if (("B".equals(o1.getStatusInd()))
        && (!("B".equals(o2.getStatusInd())))) {
        comparisonIndicator = -1;
    }
    else if (("B".equals(o2.getStatusInd()))
        && (!("B".equals(o1.getStatusInd())))) {
        comparisonIndicator = 1;
    }
    else if (("PD".equalsIgnoreCase(o1.getOfferPgm()))
        && (!"PD".equalsIgnoreCase(o2.getOfferPgm()))) {
        comparisonIndicator = -1;
    }
    else if (("PD".equalsIgnoreCase(o2.getOfferPgm()))
        && (!"PD".equalsIgnoreCase(o1.getOfferPgm()))) {
        comparisonIndicator = -1;
    }
    return comparisonIndicator;
}
公共类CustomComparator实现了Comparator,可序列化{ 私有静态最终长serialVersionUID=8040322980719271561L; @凌驾 公共整数比较(最终报价o1,最终报价o2){ int comparisonIndicator=0; if(((“B”.equals(o1.getStatusInd())) &&(!((.B.equals(o2.getStatusInd())){ 比较指示器=-1; } else if(((“B”.equals(o2.getStatusInd())) &&(!((.B.equals(o1.getStatusInd())){ 比较指示器=1; } else if(((“PD.equalsIgnoreCase(o1.getOfferPgm())) &&(!“PD”.equalsIgnoreCase(o2.getOfferPgm())){ 比较指示器=-1; } else if((((“PD.equalsIgnoreCase(o2.getOfferPgm())) &&(!“PD”.equalsIgnoreCase(o1.getOfferPgm())){ 比较指示器=-1; } 返回比较指示器; }
}

您可以这样简化它:

int status = o1.getStatusInd().toLowerCase().compareTo(o2.getStatusInd().toLowerCase());
if (status == 0)
    status = o1.getOfferPgm().toLowerCase().compareTo(o2.getOfferPgm().toLowerCase());
return status;

如果
getStatusInd
getOfferPgm
可以返回null,则需要稍微修改此代码,以避免NPE

什么是B,什么是PD。你想比较什么?首先解释你想做什么。你的值可以是
null
?基本上B和PD是状态指示器和报价程序类型的一些预定义常量。我在Arrays.sort()方法中传递这个比较器,以获得已排序的报价列表。我觉得我所写的内容非常笨拙,并希望加以改进。@Marvin yep,添加了关于它的注释为什么一种情况下为equals(),另一种情况下为equalsIgnoreCase()?