• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collection : trouble with order in a TreeSet

 
bomman sandro
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic