Lecture 13 Dynamic Collections Richard Gesick Figures from Lewis, “C# Software Solutions”, Addison Wesley
Objectives Review static vs. dynamic collections Discuss dynamic collection API Utilize a collection (example)
Arrays Allocate a contiguous section of memory Homogeneous Access via index <type> NAME[]; NAME = new <type>[SIZE];
“Dynamic” Arrays Arrays are good if you know how large the collection will be But if this isn’t known beforehand, how big is enough? One approach: Allocate for N When N is exceeded Allocate 2N and copy N into new space Free up original space for N Time consuming (memory allocation/copy)
Reallocating an Array Original When full A A
Reallocating an Array Original When full A A B
Reallocating an Array Original When full A A B
Reallocating an Array Original When full A A B
Reallocating an Array Original When full A A B null
Reallocating an Array Original When full A Garbage Collection A B null
Collection APIs Let’s not reinvent the wheel Other APIs provide access to collections using System.Collection.Generic; List – single-reference (one-way) collection LinkedList – double-reference (two-way) Queue – first in, first out (FIFO) Stack – first in, last out (FILO) Dictionary – key/value pairs Methods to sort, search, iterate across these collections
Focus on List<T> List provides for growth (dynamic) Has capacity & count Capacity = size allocated Count = number of slots used Reallocated automatically Grows when full to 2x Shrinks when count = ½ capacity (shrinks to 2/3 capacity so we don’t “thrash”) Provides pseudo-immediate access Gory details are hidden from us
List API List<T>() - Constructor (to hold stuff of type T) Add(T) - Adds object of type T to end of list Remove(T) - Deletes first occurrence of match RemoveAt(int) - Removes the object at position Sort(…) – arranges the objects Clear() – removes all objects Insert(T, int) - Adds object at specified position Searching: Contains/Exists/Find/FindAll/FindIndex/FindLast
1301 Asteroids in XNA
A Motivating Example Asteroids Game What considerations must be made? Rocks/asteroids flying around Ship Missiles What considerations must be made?
Asteroids Considerations Collection of rocks Collection of missiles Rock - position, velocity Ship - position, movement, shield Missile - position, velocity Collision Detection
Summary Array List More details of C# List<T> Fixed in size (too small/large?) Immediate access via index Don’t forget to allocate each element if needed List Dynamic in size Pseudo-immediate access More details of C# List<T> http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx