The Generic List<> Collection class

Slides:



Advertisements
Similar presentations
MATH 224 – Discrete Mathematics
Advertisements

Arrays. A group of data with same type stored under one variable. It is assumed that elements in that group are ordered in series. In C# language arrays.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Data Structures Introduction Phil Tayco Slide version 1.0 Jan 26, 2015.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
CSC 211 Data Structures Lecture 13
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
CSCI 51 Introduction to Programming March 12, 2009.
Unit 6 Repetition Processing Instructor: Brent Presley.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
CSCI 51 Introduction to Programming March 10, 2009.
Searching and Sorting Searching algorithms with simple arrays
UNIT - IV SORTING By B.Venkateswarlu Dept of CSE.
Sorting Mr. Jacobs.
Debugging with Eclipse
Lecture 10 Collections Richard Gesick.
Sort & Search Algorithms
CSC317 Selection problem q p r Randomized‐Select(A,p,r,i)
Week 4 - Friday CS221.
May 17th – Comparison Sorts
Sorting Why? Displaying in order Faster Searching Categories Internal
Lecture 14 Searching and Sorting Richard Gesick.
Introduction to Search Algorithms
Chapter 5 Ordered List.
Recitation 13 Searching and Sorting.
Modern Collections Classes
COMP 53 – Week Seven Big O Sorting.
Priority Queues and Heaps
Simple Sorting Algorithms
Introduction to Algorithms
Top Ten Words that Almost Rhyme with “Peas”
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Hash tables Hash table: a list of some fixed size, that positions elements according to an algorithm called a hash function … hash function h(element)
CS313D: Advanced Programming Language
CS1S467 GUI Programming LECTURE 11 Collections
Building Java Programs
Chapter 5 Ordered List.
CSE 143 Lecture 5 Binary search; complexity reading:
Chapter 6 Arrays Solution Opening Problem
Algorithm design and Analysis
Lecture 10 List Richard Gesick.
Algorithm An algorithm is a finite set of steps required to solve a problem. An algorithm must have following properties: Input: An algorithm must have.
CMSC 202 ArrayList Aug 9, 2007.
Lecture 11 Searching and Sorting Richard Gesick.
CSE 143 Lecture 2 Collections and ArrayIntList
Data Structures and Database Applications Arrays And Lists
Searching and Sorting 1-D Arrays
Selection Insertion and Merge
Modern Collections Classes
Building Java Programs
Simple Sorting Methods: Bubble, Selection, Insertion, Shell
Sorting "There's nothing in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The Sorting Hat, Harry Potter.
Basics of Recursion Programming with Recursion
Searching.
Building Java Programs
The Generic LinkedList<> Collection class
Data Structures Introduction
Data Structures Unsorted Arrays
Data Structures & Algorithms
Building Java Programs
Fundaments of Game Design
CSE 143 Lecture 2 ArrayIntList, binary search
Sum this up for me Let’s write a method to calculate the sum from 1 to some n public static int sum1(int n) { int sum = 0; for (int i = 1; i
Sorting.
Dynamic Array: Implementation of Stack
Module 8 – Searching & Sorting Algorithms
Arrays.
Modern Collections Classes & Generics
Presentation transcript:

The Generic List<> Collection class Modern Collections Classes

Table Of Contents

Generic List<> Overview

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);

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);

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);

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);

Warm Up Code

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

Example Problem

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

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

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

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

Methods You Must Memorize

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

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

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

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

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

Method Running Times in Big Oh notation

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”

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

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”

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

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.

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

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

When to use array vs. List<>

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

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)