Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 13 Dynamic Collections Richard Gesick

Similar presentations


Presentation on theme: "Lecture 13 Dynamic Collections Richard Gesick"— Presentation transcript:

1 Lecture 13 Dynamic Collections Richard Gesick
Figures from Lewis, “C# Software Solutions”, Addison Wesley

2 Objectives Review static vs. dynamic collections
Discuss dynamic collection API Utilize a collection (example)

3 Arrays Allocate a contiguous section of memory Homogeneous
Access via index <type> NAME[]; NAME = new <type>[SIZE];

4 “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)

5 Reallocating an Array Original When full A A

6 Reallocating an Array Original When full A A B

7 Reallocating an Array Original When full A A B

8 Reallocating an Array Original When full A A B

9 Reallocating an Array Original When full A A B null

10 Reallocating an Array Original When full A Garbage Collection A B null

11 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

12 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

13 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

14 1301 Asteroids in XNA

15 A Motivating Example Asteroids Game What considerations must be made?
Rocks/asteroids flying around Ship Missiles What considerations must be made?

16 Asteroids Considerations
Collection of rocks Collection of missiles Rock - position, velocity Ship - position, movement, shield Missile - position, velocity Collision Detection

17 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>


Download ppt "Lecture 13 Dynamic Collections Richard Gesick"

Similar presentations


Ads by Google