commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Michael A. Smith" <...@apache.org>
Subject RE: [Collections] ComparableComparator - nulls OK
Date Fri, 07 Jun 2002 19:59:30 GMT
On Fri, 7 Jun 2002, Eric Pugh wrote:
> +1,  In my sorts, having to deal with nulls is causing me difficulties as
> well..  Although I could see something like any nulls being ignored as a
> type of behavior..  Sort everything, and drop the nulls!

consider:  Comparator.compare(null, "x");

how do you drop or ignore the null when doing this compare?


> -----Original Message-----
> From: Jonathan Carlson [mailto:joncrlsn2@yahoo.com]
> Sent: Friday, June 07, 2002 3:38 PM
> To: commons-dev@jakarta.apache.org
> Subject: [Collections] ComparableComparator - nulls OK
> 
> 
> I'd like to make the case for a ComparableComparator that
> allows the sorting of nulls to the bottom.  This could be a
> flag to set on the existing class or another Comparator
> called something like NullableComparableComparator (or
> ComparableNullComparator?).

How about something like this:

public class NullFirstComparator implements Comparator {
  private Comparator c;
  public NullFirstComparator(Comparator nonNullComparator) {
    this.c = nonNullComparator;
  }
  public int compare(Object a, Object b) {
    if(a == b) return 0;
    if(a == null) return -1;
    if(b == null) return 1;
    return c.compare(a,b);
  }
}

and

public class NullLastComparator implements Comparator {
  private Comparator c;
  public NullLastComparator(Comparator nonNullComparator) {
    this.c = nonNullComparator;
  }
  public int compare(Object a, Object b) {
    if(a == b) return 0;
    if(a == null) return 1;
    if(b == null) return -1;
    return c.compare(a,b);
  }
}


That allows you to adjust the behavior of comparison to null for any 
comparator and not just the ComparableComparator.  It sounds like in 
your case (sorting nulls last using ComparableComparator), you'd use:

   new NullLastComparator(ComparableComparator.getInstance())


If that sounds reasonable, I'll add a full implementation (with a better 
"Comparator.equals" method) to the list of things on my todo list. 

regards,
michael

p.s.  I just threw together the above implementations. I wouldn't trust
it to actually sort things properly (or even compile) -- I may have
things reversed or something where nulls go first instead of last and
vice-versa.


--
To unsubscribe, e-mail:   <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>


Mime
View raw message