aspose file tools*
The moose likes Beginning Java and the fly likes Collection : trouble with order in a TreeSet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Collection : trouble with order in a TreeSet " Watch "Collection : trouble with order in a TreeSet " New topic
Author

Collection : trouble with order in a TreeSet

bomman sandro
Greenhorn

Joined: Jan 22, 2007
Posts: 4
Hi guys

I have trouble using TreeSet

in the folowing piece of code :

**************************

public SortedSet<Object1> getListeObject1Sorted() {

ArrayList lstObject1 = new ArrayList(getListeObject1());

Collections.sort(lstObject1 , GetComparator());

// 1 here lstObjet1 is ordered

2 return new TreeSet(lstObject1 );

// 3
***********************************

at line 1 the List lstObject1 is sorted (by date)..becuase i called the

sort methode of collection class using a comparator ..

But when i put this List into the TreeSet in line 2 ..This TreeSet has

lost the order i had in List lstObjet1

Can you explain me why please ?? i need a solution to keep the order i had

in lstObjet1 (objects ordered by date) after calling teh sort method

Thank you

[ September 04, 2007: Message edited by: bomman sandro ]
[ September 04, 2007: Message edited by: bomman sandro ]
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3527
    
  15
From the TreeSet API doc
The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
So, as you didn't supply a Comparator when you created the TreeSet, it will be ordered by the natural ordering of your Objects, which is obviously different to the ordering specified by your Comparator.
Unless you actually need your ArrayList to be ordered as well, just pass the unordered list to the Treemap constructor along with your Comparator.


Joanne
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collection : trouble with order in a TreeSet