• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Collection : trouble with order in a TreeSet

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
If I had asked people what they wanted, they would have said faster horses - Ford. Tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic