I am facing a very peculiar problem with TreeMap. I need store in formation in a map based on sort done on keys. I have implemented Comparator as an annonymous class for this sorting purpose at the time of intializing the TreeMap. But the treeMap is not following this sorting order as per the Comparator defined. I need to have sorted maps, sorted either date wise or String wise( i.e. Sunday, Monday ... etc). Can somebody help me in this.
You do not need to override your equals() method in the comparator, since your compare(Object o1, Object o2) method returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
The way you implemented your compare() method seems to be wrong. Do read the API for more information. Assuming your input objects have an attribute of the type Date/Timestamp, you could compare the 2 of them and return the right value accordingly.
My compare method receives String objects, which are made convertible via parseDate instance method.Date.valueOf method converts this parsed string into date object. I have teste this comperator using an normal java class, but it fails to give proper results when implemented from inside of a Statless Session Bean.
I will try and test it after removing the equlas method.
Joined: Sep 03, 2002
It is not working even without the equals method in the comperator, can you suggest something else.
Instead of converting your dates into milliseconds, why don't you use the Date objects for comparison? This will definitely work.
You could use the SimpleDateFormat to parse your string into a Date object (you can specify the format of your date string in the constrcutor).
Then the Date class provides you with 2 methods to determine if 1 Date is before or after another. Then you can return negative, positive or zero value accordingly.
I've tried it this way many times & it works. Please refer to the Java API for java.text.SimpleDateFormat & java.util.Date for more information.
Joined: Sep 03, 2002
The Treemap is getting sorted at the back end, that is in the session bean, I have printed its contents out there.But as i am using a data transfer object for bringing this TreeMap to the front end, as soon as i assign this TreeMap refference to the the setDatamap() method of this dto, it looses its order.Dto has among many methods a method for setting the map to itself :
Can you suggest some way out. Am really stuck over here.
Do you have control over the front end? If so, then change the front end to do the sorting.
SCJP 1.4, SCWCD 1.3, SCBCD 1.3
Joined: Apr 02, 2004
A simple solution is available if your DTO codes is what you posted.
You don't have to instantiate your local copy of the TreeMap inside your DTO. The order was lost because of you instantiated a TreeMap object without any Comparator object & hence when you passed in your sorted map, it took the natural order again.