Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Generic List<> Collection class

Similar presentations


Presentation on theme: "The Generic List<> Collection class"— Presentation transcript:

1 The Generic List<> Collection class
Modern Collections Classes

2 Table Of Contents

3 Generic List<> Overview

4 A List<> is an array with more features
10 1 20 2 3 200 List<> object The Stack Main() nums numList static void Main(string[] args) { int[] nums = { 10, 20, 2, 200 }; // let's copy nums into a List<> List<int> numList = new List<int>( nums ); numList.Add(20); numList.Insert(1, 7); numList.Remove(20);

5 List<> will automatically resize
10 1 20 2 3 200 List<> object The Stack Main() nums numList 4 static void Main(string[] args) { int[] nums = { 10, 20, 2, 200 }; // let's copy nums into a List<> List<int> numList = new List<int>( nums ); numList.Add(20); numList.Insert(1, 7); numList.Remove(20);

6 List<> will automatically resize AND slide elements over to make space
5 20 10 2 3 4 200 1 List<> object The Stack Main() nums numList 7 static void Main(string[] args) { int[] nums = { 10, 20, 2, 200 }; // let's copy nums into a List<> List<int> numList = new List<int>( nums ); numList.Add(20); numList.Insert(1, 7); numList.Remove(20);

7 List<> will find and remove elements, compressing the remaining elements
10 2 3 200 4 20 1 List<> object The Stack Main() nums numList 5 7 static void Main(string[] args) { int[] nums = { 10, 20, 2, 200 }; // let's copy nums into a List<> List<int> numList = new List<int>( nums ); numList.Add(20); numList.Insert(1, 7); numList.Remove(20);

8 Warm Up Code

9 MSDN Example Please look at the example code in the MSDN documentation for List<> This code was already discussed in the ‘Collections Overview’ slides so we will not examine them again here

10 Example Problem

11 Record the numbers that the user types in
Let’s write a program that does the following: Repeat the following until the user wants to quit (or clear the list and start over) Prompt the user to type something in Put that new item in a random spot in the list of things the user has typed Print out the entire list

12 Record numbers that the user types: Why is List<> a good choice?
List<> will auto-resize as the program gets more inputs List<> when you need to store a bunch of stuff in an arbitrary order As opposed to storing the numbers from smallest to largest List<> allows us to add / remove stuff wherever we want At the start In the middle At the end There’s an Add() method that does this

13 Is List<> always a good choice?
It depends on the problem For example, what if the program should print out all the numbers AND print out the Minimum Maximum Median A sorted (ordered) Collection would be better For example, there is a SortedSet

14 public void ExampleProgram() { Random rand = new Random(); List<int> nums = new List<int>(); int nextNum = 0; while (nextNum != -1) { do { Console.WriteLine("Type in your next number!\n\tType -1 to quit\n\tType -2 to start over"); } while (Int32.TryParse(Console.ReadLine(), out nextNum) == false); switch (nextNum) { case -1: Console.WriteLine("You typed -1, to quit. Bye bye!"); // could do a Environment.Exit(0); here // while(nextNum != -1) will stop, causing the program to exit break; case -2: Console.WriteLine("You typed -1, start over. Removing all numbers now!"); nums.Clear(); break; default: int location = rand.Next(0, nums.Count); nums.Insert(location, nextNum); Console.WriteLine("You've printed out:"); foreach (int num in nums) { Console.Write("{0}, ", num); } Console.WriteLine(); break; } } } Example Solution

15 Methods You Must Memorize

16 Useful Methods And Properties
The Count property (how many items are in the list) The Capacity property (how many spaces the list has in it’s array) Add: Adding new elements to the end of the list Insert: Adding new elements into the middle of the list Remove: Removing an individual element from the list Clear: Remove everything from the list foreach loop

17 More Useful Methods Contains: Find an element by doing a linear search
Know that IndexOf exists. Know that LastIndexOf also exists These are all O(N) Sort: Rearrange the list to be in the ‘normal’, default order Know that other versions of this exist, in case you want a different order (highest to lowest, for example) BinarySearch: Once the array is in a particular order, you can search it in O(lgN) time

18 How is List<> implemented?
How can we figure this out on our own?

19 Search The Web Googling for it Example Results:
“c# how is list<> implemented” “c# how does list<> work” Example Results: StackOverflow - What's the implementation of List? StackOverflow - What is a list in C# and how does it work? [duplicate] StackOverflow - How is List<T>.IndexOf() implemented in C#? MSDN – The List: a Homogeneous, Self-Redimensioning Array

20 Examining Source Code You can look at the source code
For example, the Add method: // Adds the given object to the end of this list. The size of the list is // increased by one. If required, the capacity of the list is doubled // before adding the new element. // public void Add(T item) { if (_size == _items.Length) EnsureCapacity(_size + 1); _items[_size++] = item; _version++; } the above is ‘add to array’ code

21 Method Running Times in Big Oh notation

22 The Insert Method: What the docs say
From the MSDN docs: “This method is an O(n) operation, where n is Count.” In other words, if there are N elements in the List, we expect an Insert operation to take O(N), aka “at most linear time”

23 The Insert Method: O(N)
Calling Insert causes the List to move everything over by a space (If needed, the List will resize the array by creating a new, bigger array, and then copying everything over into that new array) The List will then add the new element to the open space Remember that Big Oh is an upper bound. Inserting near the end isn’t really linear In the worst case (upper bound) we insert at the beginning List<> object (before Insert) 10 2 3 200 4 20 1 List<> object (moving stuff) 5 20 10 2 3 4 200 1 ??? List<> object (after Insert) 5 20 10 2 3 4 200 1 7

24 The Remove Method: What the docs say
From the MSDN docs: “This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.” In other words, if there are N elements in the List, we expect a Remove operation to take O(N), aka “at most linear time”

25 The Remove Method: O(N)
Calling Remove causes the List to move everything down by a space (If needed, the List will resize the array by creating a new, bigger array, and then copying everything over into that new array) The List will then put the default value (0 for integers) into the right- most, now open, space Remember that Big Oh is an upper bound. Removing near the end isn’t really linear In the worst case (upper bound) we remove from the beginning 1 2 3 4 5 List<> object (Find target) 10 7 20 2 200 20 List<> object (move everything) 10 2 3 200 4 20 1 5 20 1 2 3 4 5 List<> object (Finished) 10 20 2 200 20

26 The Add Method: What the docs say
From the MSDN docs: If Count is less than Capacity, this method is an O(1) operation. If the capacity needs to be increased to accommodate the new element, this method becomes an O(n) operation, where n is Count.

27 The Add Method: The O(1) scenario
Add(x) will place x at the end of the list O(1) scenario: If the internal array has extra, unused spaces, then the Add() method will add the new value to the end of the array immediately Count = number if items in the List right now Capacity = number of spaces in the internal array List<> object Capacity = 6 Count = 4 5 10 2 20 3 4 1 7 Found empty space here! List<> object (Finished) 5 10 2 3 200 4 20 1

28 The Add Method: The O(N) scenario
Add(x) will place x at the end of the list O(N) scenario: The List’s Count is the same as the Capacity Meaning: we don’t have any unused spaces in the list’s array Step 1: create a new, empty array that’s bigger This requires O(N) time Step 2: copy all the values from the current array into the new one Step 3: switch to using the new array Step 4: Place the value into the next available space in the (new) array 1 2 List<> object (Find target) 10 7 20 10 20 7 5 2 3 10 4 1 List<> object (Finished) 5 10 2 3 4 1 20 77

29 When to use array vs. List<>

30 When to use List<> vs. C# array?
Short version: use List<>, unless you have a good reason not to Some examples of a good reason: You need to call a method that returns an array or requires an array as a parameter Lower-level work (OS’s often use arrays – network interfaces, images, etc) Arrays perform better First write the program with List<>, then switch to array only if you need the perf benefit  Arrays are good when you know you have a fixed-length storage need Arrays are good for 2D storage (particularly dense/packed storage) List<> is easier to use, and has more features. Line-of-business apps should prefer this

31 Sources for List<> vs. C# array
StackOverflow: When to use a basic array or a List<> Blog post: Arrays considered somewhat harmful StackOverlow: Array vs. List<>: when to use which? List<> can be made read-only (StackOverflow)


Download ppt "The Generic List<> Collection class"

Similar presentations


Ads by Google