Array to List

Monkey Forums/Monkey Programming/Array to List

Chroma(Posted 2013) [#1]
I was trying not to post something about it and I have it "working" but is there an easier way to turn an array into a list and back.

I'm looking to do the stuff below (pseudocode)

list:String[] = mystring.Split(",")

myList:List = myArray.ToList()

Thanks,


Chroma(Posted 2013) [#2]
Also I'm writing a CopyList function but I want it to be generic. I have a class called Obj for example but I want this to work with all classes.

Local tempList:List<Obj> = CopyList(myList)


Function CopyList:List<Object>(list:List<Object>)
	Local temp:List<Object> = New List<Object>
	For Local o:Object = Eachin list
		temp.AddLast(o)
	Next
	Return temp
End function



Belimoth(Posted 2013) [#3]
For that second one, you should follow the example of Diddy's 'Arrays' class and bundle it up like this:
Class Lists<T>
	Function Copy:List<T>(list:List<T>)
		Local temp := New List<T>
		For Local t := EachIn list
			temp.AddLast(t)
		Next
		Return temp
	End
End 


Usage:
Strict

Class Foo
	Field value:Int
	
	Method New(value:Int)
		Self.value = value
	End
End

Class Lists<T>
	Function Copy:List<T>(list:List<T>)
		Local temp := New List<T>
		For Local t := EachIn list
			temp.AddLast(t)
		Next
		Return temp
	End
End

Function Main:Int()
	Local myList := New List<Foo>()
	myList.AddLast( New Foo(1) )
	myList.AddLast( New Foo(2) )
	myList.AddLast( New Foo(3) )
	
	Local myCopy := Lists<Foo>.Copy(myList)
	For Local foo := EachIn myCopy
		Print foo.value
	Next
	
	Return 0
End



Chroma(Posted 2013) [#4]
Can this also be done with a Stack? I was using Stack<T> and it didn't work.


Beaker(Posted 2013) [#5]
You don't need all that code:
Local arr:String[] = ["a","b","c","d","e"]
Local list:List<String> = New List<String>(arr)
For Local s:String = Eachin list
	Print "list item="+s
End
arr = list.ToArray()
For Local i:= 0 Until arr.Length
	Print "array item "+i+"="+arr[i]
End



wiebow(Posted 2013) [#6]
rtfm? :)


Belimoth(Posted 2013) [#7]
Oh wow, I never noticed that constructor in the List class before.
That means we can cheat for the copying if performance isn't a concern:
myCopy = New List( myList.ToArray() )



Beaker(Posted 2013) [#8]
That would also work for a Stack.


Chroma(Posted 2013) [#9]
Wow thanks...working on this now.


Chroma(Posted 2013) [#10]
Yep works like a charm. The Obj is just a custom class of mine.
Local temp_array:Obj[] = Self.obj_stack.ToArray()                   'Stack to Array
Local temp_stack:Stack<Obj> = New Stack<Obj>(temp_array)            'Array to Stack
Local temp_stack:Stack<Obj> = New Stack<Obj>(obj_stack.ToArray())   'Stack to Stack
Local temp_list:List<Obj> = New List<Obj>(obj_stack.ToArray())      'Stack to List
Local temp_stack:Stack<Obj> = New Stack<Obj>(temp_list.ToArray())   'List to Stack



NoOdle(Posted 2013) [#11]
doh I hadn't noticed that either! Wondering now If I have actually needed it in the past.. not sure I have.