Sorting an array of null objects

BlitzMax Forums/BlitzMax Programming/Sorting an array of null objects

Perturbatio(Posted 2005) [#1]
Not sure whether this should happen or not.

If you do:

Local a:Object[5]

Rem 
'uncomment this to solve it since they are no longer null
For Local i:Int = 0 To 4
	a[i] = New TImage
Next
EndRem

a.sort()



It causes an unhandled memory exception.

I realise this is because it's trying to access the compare method of the null object, but would it not be better to simply stop the sort there rather than throw an exception?

*EDIT*
for instance, the first two elements could contain a valid object, but the array can't be sorted until all elements are valid.


degac(Posted 2005) [#2]
Or I have some spirit in my computer - but I copied your code, run it with debug mode on - but nothing happens (=no errors)

[edit] I must stop drinking...:P - You are right!


Azathoth(Posted 2005) [#3]
I think its because sort calls the compare method of all the objects, any that are null would raise an exception.


Perturbatio(Posted 2005) [#4]

I realise this is because it's trying to access the compare method of the null object, but would it not be better to simply stop the sort there rather than throw an exception?



Dreamora(Posted 2005) [#5]
You could modify the implementation of sort to reflect this behavior.
But if you know that there will be "null" objects, you should perhaps prefer lists ... this would speed up the sorting as well ...


Azathoth(Posted 2005) [#6]
Isn't it possible to catch the exception?


Perturbatio(Posted 2005) [#7]
Isn't it possible to catch the exception?

nope. enclosing it in a try-catch block doesn't help.


Azathoth(Posted 2005) [#8]
This works
Local a:Object[5]

Rem 
'uncomment this to solve it since they are no longer null
For Local i:Int = 0 To 4
	a[i] = New TImage
Next
EndRem

Try
	a.sort()
Catch except:TRuntimeException
	Print except.ToString()
EndTry