I am doing sort on an ArrayList and I am using the below code, the sortField here is of type string which works perfectly fine but sometimes it can also be a field of type Date and the below is throwing a class cast exception in that case. What needs to be used such that it works in both the scenarios. Thanks a lot for the help in advance.
Collections.sort(tempList, new BeanComparator(sortField, String.CASE_INSENSITIVE_ORDER));
Akshitha Mishra wrote:Can you please provide any pointers.
I believe Joanne already did.
Also, is it possible that I can sort by string or date in the same implementation
What do you mean by "the same implementation"?
However, just off the top of my head I'd say that it's probably not a good idea. You have to supply A Comparator to sort(), and that will only order your objects in one way.
My suggestion: Why don't you give us some background and explain WHAT it is you want to do, rather than HOW you want to do it? That way, we might be able to offer some better advice.
Akshitha Mishra wrote:If the sortField value is String, then I want it be sorted by String, but if the sortField value is date, then I want it to be sorted by Date.
I understand that; and if the field is Comparable (and both Strings and Dates are), then you can probably do it. For example, I wrote the following class a while ago:Now it may not look like much, but it allows you to create a Comparator for any Comparable type that emulates its "natural" order; and that means that you can use Comparators pretty much everywhere.
But the collections.sort that I am using works only for strings and not when I need it to be sorted by date.
Then you're doing something wrong, because it will sort by either; just not at the same time, or with the same Comparator. Now if that's what you want, then you'll probably need some pretty fancy code...and it may well be slow.
However, you still haven't explained what you're trying to do. Perhaps these are easier questions:
Why do you need to do this? And why can't you just write two different sort() calls?
Akshitha Mishra wrote:My ArrayList is an object that contains multiple fields
Just saw this: No it isn't - or, if it is, then it isn't a java.util.ArrayList.
What I suspect you mean is that it contains objects that have multiple fields, and that's quite different.
If you need those objects to be sortable by any of their fields, then you need to define Comparators for them - and the best place to do that is probably in the class itself (and personally, I quite like using a nested enum for that).
Ordering is the responsibility of the class being ordered, not the List that holds them.