Collections.sort in 1.5

M

Myriam Abramson

I have:

Vector<MyClass> v = new Vector<MyClass>();

Collections.sort(v);

Now, MyClass implements Comparable but Collections.sort seems to
ignore it. I would think that the order coded in the compareTo method
in MyClass would be the natural order of instances of this class, no?
I had to create a Comparator class to tell Collections.sort how to
sort correctly. Why having those annotations if they are not picked up
correctly? Again I have Java 1.5. Thanks for any insights.

myriam
 
H

hiwa

Myriam Abramson ã®ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸:
I have:

Vector<MyClass> v = new Vector<MyClass>();

Collections.sort(v);

Now, MyClass implements Comparable but Collections.sort seems to
ignore it. I would think that the order coded in the compareTo method
in MyClass would be the natural order of instances of this class, no?
I had to create a Comparator class to tell Collections.sort how to
sort correctly. Why having those annotations if they are not picked up
correctly? Again I have Java 1.5. Thanks for any insights.

myriam
Your mplementation of equals() and hashCode() issue, or other
issue(s)...
Post a small demo code that is generally compilable, runnable and could
reproduce your problem. See:
http://homepage1.nifty.com/algafield/sscce.html
 
P

Patricia Shanahan

Myriam said:
I have:

Vector<MyClass> v = new Vector<MyClass>();

Collections.sort(v);

Now, MyClass implements Comparable but Collections.sort seems to
ignore it. I would think that the order coded in the compareTo method
in MyClass would be the natural order of instances of this class, no?
I had to create a Comparator class to tell Collections.sort how to
sort correctly. Why having those annotations if they are not picked up
correctly? Again I have Java 1.5. Thanks for any insights.

Interesting. There has to be something special going on here, because
Collections.sort normally deals correctly with Comparable. I second the
request for a short, self-contained, compilable example.

I can think of some explanations, but they depend on how MyClass is
defined. For example, it could extend a Comparable class and not itself
provide a public compareTo(Object), only a compareTo(MyClass). In that
case, the sort would be according to the parent class natural order.

The quickest way to find out what is really going on will be an example.

Patricia
 

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,266
Messages
2,571,075
Members
48,772
Latest member
Backspace Studios

Latest Threads

Top