How to refer to sorted data?

J

Jacob

Can I be sure that iterating over "sorted" will
always return elements in sorted order:

Collection sorted = new TreeSet (unsorted);

Or must I do this to be 100% certain:

TreeSet sorted = new TreeSet (unsorted);

Thanks!
 
J

Joona I Palaste

Jacob said:
Can I be sure that iterating over "sorted" will
always return elements in sorted order:
Collection sorted = new TreeSet (unsorted);
Or must I do this to be 100% certain:
TreeSet sorted = new TreeSet (unsorted);

The first way will do just fine. The object will not magically change
just because it's referred to by a variable of a different type.
 
M

Michael Borgwardt

Jacob said:
Can I be sure that iterating over "sorted" will
always return elements in sorted order:

Collection sorted = new TreeSet (unsorted);

Or must I do this to be 100% certain:

TreeSet sorted = new TreeSet (unsorted);

No, that's not necessary. In both cases, calling
iterator() on the collection will polymorphically
resolve to the implementation in the
TreeSet class, which returns the elements in sorted
order. In fact there isn't even a theoretical other
possibility since Collection is an interface and
this cannnot have an implementation and the
superclasses of TreeSet don't provide a default
implementation of iterator(), which is abstract
in AbstractCollection.
 
R

Roedy Green

Collection sorted = new TreeSet (unsorted);
Try the experiment. You will find that the enumeration you actually
get is the same in both cases through the magic of polymorphism.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top