tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From DJohn...@desknetinc.com
Subject Re: This is just plain ... odd.
Date Thu, 08 Nov 2012 15:05:43 GMT
Russ Kepler <russ@kepler-eng.com> wrote on 11/08/2012 09:22:41 AM:

> From: Russ Kepler <russ@kepler-eng.com>
> To: Tomcat Users List <users@tomcat.apache.org>, 
> Date: 11/08/2012 09:23 AM
> Subject: Re: This is just plain ... odd.
> 
> On Thursday, November 08, 2012 01:35:55 PM Lyallex wrote:

> > I have tried everything I can think of to reproduce this behaviour
> > in a standalone Java program but the list is always returned
> > as required. When I call the method from a servlet the list is always
> > returned
> > in it's natural order, I know collections.sort is being executed as
> > the list is in alpha order, it's almost as if the comparator is being
> > replaced in some way
> >
> > I have no servlet filters or any other code 'in the way' between the 
facade
> > and the initialization servlet.
> >
> > Any ideas ?

> I'm not sure that you can ever get consistent results if the input order 
is
> random.  The Collections.sort() implements a merge sort and the merge 
sort
> depends on a consistent result from the compare() method.  As 
implemented the
> compare() will return what you want when the object being compared 
against is
> the "Misc" object but return a string compare when it isn't.  Try this:

> @Override
> public int compareTo(Category c) {
> if(category.equals("Miscellaneous")){
> return 1;
> } elseif (c.category.equals("Miscellaneous")) {
> return -1;
> else{
> return category.compareTo(c.category);
> }
> }

> (side comment: If the list is a decent size it might make sense to 
compare
> against the Misc object rather than compare all strings but it's likely 
not
> worth the bother).

> The was I usually handle this is to .remove the offending object 
> from the list,
> sort, then .add it back on after the sort.  Keep the odd code local to 
the
> oddity.

This is closer, but still doesn't work correctly if two "Misc" categories 
are being compared, or one "Misc" category is compared to itself. 
Try: 

@Override
public int compareTo(Category c) {
        if(category.equals("Miscellaneous")) {
                if(category.equals(c.category) return 0; // correctly 
handle equality. 
                else return 1;
        } elseif (c.category.equals("Miscellaneous")) {
                return -1;
        } else {
                return category.compareTo(c.category);
        }
}

---------------------------------------------------
David S. Johnson
DeskNet Inc.




Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message