How can i sort ArrayList in java without using comparator.?
I have already used comparator and it work not properly for me, means data is not in particuler manner.
I have one array list that contain following properties…
getTotal(),
getID(),
getRank(),
getItemName(),
getFinalRank()
I have sotred this all this into one arraylist itemWiseDetails
now i want to make poi report and display all this details but according to rank of that
itemName. ANd one more thing my rank is in String so when i Tried to sort based on this rank it take N/A data as a 0 rank so it displayed first then it display first rank , then second and go on ..
So, I want to sort this itemWiseDetails list without comparator
Thanks in advance,
I have implement Comparator like this way
public int compareTo(Object itemDetailVO)
{
if (!(itemDetailVOinstanceof ItemDetailVO)) throw new ClassCastException("AItemDetailVOobject expected.");
int otherItemRank = Integer.parseInt(((ItemDetailVO) itemDetailVO).getRank().toString());
return Integer.parseInt(this.trLotRank.toString())- otherBidderRank;
}
You have two options:
Comparable, and callCollections.sortwithout specifying a comparatorYou seem to be taking the approach of “I tried X and it didn’t work, therefore I need to try something else” – but the reason X (using a comparator) didn’t work appears to be that your comparator had bugs… it didn’t compare items in the way that you wanted it to. You’ll run into exactly the same problem when you implement
Comparable. You’ve still got the same fundamental work to do (working out how to compare two items) – it’s really just a matter of where that logic goes.Generally implementing a
Comparatoris a more flexible approach, in that it allows a collection to be sorted in different ways depending on your needs. It also allows you to sort collections where you can’t change the code within the element class itself. I would personally stick to theComparatorapproach.Write some unit tests comparing various items, and then implement the comparator so that those tests pass. Then if you see any more problems, add a test for that case and make that pass too. Iterate until your comparator is working properly.