Method sort breaks removelist?

BlitzMax Forums/BlitzMax Beginners Area/Method sort breaks removelist?

coffeedotbean(Posted 2009) [#1]
Took me an hour to work out what was wrong, I added some sort code to sort my TList and suddenly listremove no longer works.

Commenting out the Sort.List() call does not work I have to comment out the whole method block.

Broken code (added method & list.sort()) list is sorted

Graphics 640,480,0,0
SeedRnd MilliSecs()

Global LBobs:TList=New TList
Type TBobs
	Field x,y
	
	Method Compare:Int(Other:Object)
		If y < TBobs(Other).y Then Return 1 Else Return -1
	End Method
	
End Type

For x = 0 To 999 ; make() ; Next

Repeat ; Delay 5 ; Cls
	
	LBobs.sort()
	
	For b:TBobs = EachIn LBobs
		DrawRect b.x,b.y,10,10 		
	Next
	
	For b:TBobs = EachIn LBobs
		If MouseX()>b.x And MouseX()<b.x+10 And MouseY()>b.y And MouseY()<b.y+10 Then ListRemove(LBobs,b) 		
	Next
	
	DrawText CountList(LBobs),10,10
	
Flip ; Until KeyDown(KEY_ESCAPE) ; End 

Function make()
	
	b:TBobs = New TBobs
	ListAddLast LBobs , b
		b.x	= Rand(0,640)
		b.y	= Rand(0,480)
	
End Function


working code (without method) but list not sorted

Graphics 640,480,0,0
SeedRnd MilliSecs()

Global LBobs:TList=New TList
Type TBobs
	Field x,y
End Type

For x = 0 To 999 ; make() ; Next

Repeat ; Delay 5 ; Cls
	
	'LBobs.sort()
	
	For b:TBobs = EachIn LBobs
		DrawRect b.x,b.y,10,10 		
	Next
	
	For b:TBobs = EachIn LBobs
		If MouseX()>b.x And MouseX()<b.x+10 And MouseY()>b.y And MouseY()<b.y+10 Then ListRemove(LBobs,b) 		
	Next
	
	DrawText CountList(LBobs),10,10
	
Flip ; Until KeyDown(KEY_ESCAPE) ; End 

Function make()
	
	b:TBobs = New TBobs
	ListAddLast LBobs , b
		b.x	= Rand(0,640)
		b.y	= Rand(0,480)
	
End Function


I really cannot get my noddle around why it breaks removelist.


degac(Posted 2009) [#2]
Interesting...

I changed your code to manage LINK and its method Remove to detach it from the list. It seems to work.
I dont' know why with ListRemove command it doesnt' work..

edit:

This is the original source code from brl.LinkedList - the method FindLink is used by ListRemove.
Rem
	bbdoc: Returns the first link in the list with the given value, or null if none found.
	End Rem
	Method FindLink:TLink( value:Object )
		Local link:TLink=_head._succ
		While link<>_head
			If link._value.Compare( value )=0 Return link
			link=link._succ
		Wend
	End Method

It seems that your Compare Method 'override' the default behaviour: there'll be never a '0' value, so no link, no remove.
So the solution - if you want to use ListRemove is to change your method

	Method Compare:Int(Other:Object)

		If other=Null Return 0

		If y=tbobs(other).y Return 0
		If y < TBobs(Other).y Then Return 1 Else Return -1
	End Method



coffeedotbean(Posted 2009) [#3]
WOW, thanks degac.

Still so much to learn about lists.