File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Sorting problem using CompareTo Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting problem using CompareTo" Watch "Sorting problem using CompareTo" New topic
Author

Sorting problem using CompareTo

Mike London
Ranch Hand

Joined: Jul 12, 2002
Posts: 1066
Hi,

I have a table that I'm trying to sort using a CompareTo.

The problem is that the table I'm sorting has strings, ints, and dates so when I click the integer column, it "sorts", but not correctly.

As you can see, the code below works with Strings. I need to adapt it, if possible, to work with ints and Dates.

The code I'm adapting from a Sun sample is:

protected void sort(final String column, final boolean ascending)
{
Comparator comparator = new Comparator()
{
public int compare(Object o1, Object o2)
{
SimpleCar c1 = (SimpleCar)o1;
SimpleCar c2 = (SimpleCar)o2;
if (column == null)
{
return 0;
}
if (column.equals("type"))
{
return ascending ? c1.getType().compareTo(c2.getType()) : c2.getType().compareTo(c1.getType());
}
else if (column.equals("color"))
{
return ascending ? c1.getColor().compareTo(c2.getColor()) : c2.getColor().compareTo(c1.getColor());
}
else return 0;
}
};
Collections.sort(_cars, comparator);

-===========================================

Is there a way, using this basic code to sort a column if it's an "int"?

I've tried messing around with this and the compareTo, but I keep getting errors.

I also have a Date column I would like to sort.

The user can click on any column to sort by that column.

Look forward to any suggestions!!!

Thansks ...

-- Mike
uj johansson
Greenhorn

Joined: Dec 31, 2005
Posts: 23
Yes there is. Instead of considering Strings you consider ints, or any other type you want to compare.

Ask yourself: Do I understand why I supply a Comparator object to a sort call? Do I understand what the Comparator object should return?
Mike London
Ranch Hand

Joined: Jul 12, 2002
Posts: 1066
Hi,

Since compareTo only works with objects, I can't compare ints directly.

I tried using Integers, by wrapping the String into an Integer, but that didn't work either. (Error!, not -1, 0, or 1)

Can you be a little more specific with your reply or perhaps post a tiny bit of pseudo code?

Thanks.

-- Mike
Mike London
Ranch Hand

Joined: Jul 12, 2002
Posts: 1066
Duh!

My problem was I was using an Integer wrapper on a Float field!

No wonder my Comparator didn't work!

Too bleary-eyed to notice it initially I guess.

Thanks.

-- Mike
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting problem using CompareTo