Compare method and equality
Monkey Forums/Monkey Programming/Compare method and equality
| ||
Hello, I have played a bit with the Compare() method from the List. It doesn't seem to have any info on this but i was wondering what happen when an "Object A" equals "Object B". From another post.. it seemed to return 0. Class UnitList Extends List<Unit> Method Compare:Int(a:Unit, b:Unit) If a.speedFactor > b.speedFactor Return 1 If a.speedFactor = b.speedFactor Return 0 Return -1 End End But how does it decide which one to take if they are identical ? What the return value exactly do ? If i print the values.. they seem a bit off from the original value when they pass in the compare method. Here the output when they are identical. Any ideas why i am getting thoses values ? ObjectA: 6.300000000000001 ObjectB: 6.3999999999999995 Thanks ! |
| ||
As fare as I know the COMPARE() does not return any object or does manipulate the values. It only return, what you wrote in: return a INTEGER value "1" if the first is bigger return a INTEGER value "0" if both are equal return a INTEGER value "-1" if the second is bigger the LIST.SORT() function uses this returned values to decide, whether to swap the positions of the both objects in the list when sorting the list. The inaccuracy of your object values like A.SpeedFactor# is not caused by the COMPARE(), but by the fact, that you use FLOAT type to store the values. And the are already before COMPARE() inaccurate. Test it! |
| ||
But if both are equals.. What happening ? I mean.. what the 0 actually do ? |
| ||
when sorting, if both objects are, equal they will not be sorted and will continue with the next element. |
| ||
I see. Thanks for the info :) i think i will have to handle manually what im trying to do. Since its a turn list for a role-playing game i was sorting i will probably go random between 1 and -1 if both are equal. Thanks! |
| ||
That what the Compare() is for: manually decide what to do. You are not forced to put the three statements in the Method as given. You can add your random line direct into the Compare(). [monkeycode]Class UnitList Extends List<Unit> Method Compare:Int(a:Unit, b:Unit) If a.speedFactor > b.speedFactor Return 1 If a.speedFactor < b.speedFactor Return -1 ' when equal do a Rnd -1 or 0 or 1: Return Int(Rnd(0,3))-1 End End [/monkeycode] You can modify Compare() to find Doubles: [monkeycode]Global IsThereADouble% Class UnitList Extends List<Unit> Method Compare:Int(a:Unit, b:Unit) If a.speedFactor > b.speedFactor Return 0 If a.speedFactor < b.speedFactor Return 0 ' when equal: IsThereADouble=True Return 0 End End [/monkeycode] |
| ||
Alright thanks for you help :) |
| ||
If you use Diddy's ArrayList, you can just make your class implement IComparable. No need to extend List. |