Hi, I have a problem to with sorting some elements.
I have a class Test1 which implements Comparable and so has as compareTo-method:
Next I have class Test2, that has a relation to Test1. Every Test2 has one associated Test1. To order a set of Test2-objects I want to use the associated Test1-objects (by comparing them throw compareTo()).
Now I want to order a Set of Test2 with the help of their associated Test1-class. But it doesn't work:
Any ideas what I'm doing wrong?
Klaus [ January 30, 2005: Message edited by: Klaus Jesper ]
Originally posted by Klaus Jesper: Now I want to order a Set of Test2 with the help of their associated Test1-class. But it doesn't work
By this do you mean
You get a compile error
You get a runtime error (exception)
The program runs but the ordering is incorrect
??? I like a good puzzle, but you have to give us all the pieces!
This expressionlooks suspicious. Does Test2 contain the following member field?If not, Test2 doesn't really contain a Test1. If so, you need to reference Test2's field name -- not the name of the class the field references.
Originally posted by Jeroen Wenting: In that case the Test2 class should implement Comparable and have that test on the Test1 field, not like this with Test1 implementing Comparable.
I disagree. What if Test2s were being ordered by a String field in Test2? Would you reimplement String-comparison inside Test2 or use String's compareTo() method?
Klaus, I suspect that in retyping those classes here you have managed to fix the problem. In other words, you probably have a typo in the originals. Why do I say this? Because I just ran your code (adding only constructors) and it works beautifully.The output is 1 ... 9, each on its own line, as expected.
One thought. If you allow duplicate order numbers, you'll get incorrect behavior. You need to initialize returnValue to 0 in Test1 otherwise you return -1 for equal orderNo values. I assumed you didn't have duplicates.
you call compareTo() on String from inside the compareTo() in your Test2 class. You can do the same thing here. But you're NOT supposed to expect to be able to compare 2 Test2 objects from inside a Test1 instance which is what the OP seems to be trying to achieve.