what is an array? int string decimal int string decimal int string decimal int decimal...

51
ARRAYS AND COLLECTIONS

Upload: camron-mckinney

Post on 02-Jan-2016

273 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

ARRAYS AND COLLECTIONS

Page 2: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

What is an array?

int

string

decimal

int

string

decimal

int

string

decimal

int

decimal decimal

“Elements” in the array

We can declare variablesfor individual values.

We can also declare an “array”of values.

Page 3: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Declaring an Array

int0

int0

int0

int0

But an array is much easier…

int[] highScores;highScores = new int[5];

We could do…

int highScore1 = 0;int highScore2 = 0;int highScore3 = 0;int highScore4 = 0;int highScore5 = 0;

Tip: Declare and initialize on the same line.

int[] highScores = new int[5];

int0

Track top five high scores in a game…

Page 4: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Initializing an Array

We can initialize elements individually…

int[] highScores = new int[5];

// First element is at index 0 highScores[0] = 5000;highScores[1] = 5000;highScores[2] = 5000;highScores[3] = 5000;highScores[4] = 5000;

Or we can initialize elements during creation of the array…

int[] highScores = new int[5] { 5000, 5000, 5000, 5000, 5000 };

Arrays are automatically initialized to default values, but thosevalues may not suit your purposes.

Page 5: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Using an ArrayWhat if the array size changes?

int[] highScores = new int[20] { 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000 };

Use a loop…

int[] highScores = new int[20];

for (int index = 0; index < 20; ++index ){ highScores[index] = 5000;}

Tip: Define constants instead of using hard-coded values to defineand initialize an array.

const int NUM_HIGH_SCORES = 20;const int MIN_HIGH_SCORE = 5000;

int[] highScores = new int[NUM_HIGH_SCORES];

for (int index = 0; index < highScores.Length; ++index ){ highScores[index] = MIN_HIGH_SCORE;}

How could you improve this further?

Page 6: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Iterating Over an Array

for (int index = 0; index < highScores.Length; ++index){ int score = highScores[index]; file.writeScore(score);}

foreach (int score in highScores){ file.writeScore(score);}

What if we need to access each element in an array?

Page 7: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Rectangular Arrays

int0

int0

int0

int0

int[,] highScores = new int[NUM_DAYS, NUM_HIGH_SCORES];

int0

Track top five high scores in a game for the last three days…

int0

int0

int0

int0

int0int

0int0

int0

int0

int0

for (int day = 0; day < highScores.GetLength(0); ++day){ for (int score = 0; score < highScores.GetLength(1); ++score) { highScores[day, score] = MIN_HIGH_SCORE; }}

Page 8: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

What is a jagged array?

int[][] highScores = new int[12][];highScores[0] = new int[31];highScores[1] = new int[29];...

A jagged array is an array where each element is an array.

Page 9: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Initialize a Jagged Arrayint[][] highScores = new int[12][];

int[] days = new int[] { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

for (int month = 0; month < highScores.GetLength(0); ++month){ highScores[month] = new int[days[month]];

for (int day = 0; day < highScores[month].Length; ++day) { highScores[month][day] = MIN_HIGH_SCORE; }}

Page 10: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

The params keyword

int avg = CalculateAverage(5, 8, 32, 17, 9, 26);

We can gather method arguments into an array.

int CalculateAverage(params int[] values){ int sum = 0; foreach (int value in values) { sum += value; } return sum / values.Length;}

Page 11: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Working with Arraysstring[] lastNames = new string[] { “Smith”, “Newton”, “James”, “Wells”, “Alexander”, “Milton”, “Cooper”, “Ashe”, “Horton” };

int index = Array.BinarySearch(lastNames, “B”);

Array.Sort(lastNames);

string[] aNames = new string[~index];Array.Copy(lastNames, aNames, ~index);

Page 12: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

When to Use Arrays?

What are some things we might model using arrays?

Icons on your phone Security cameras around an office Playlists Distribution list on an email

Page 13: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Key Ideas for Arrays

Fixed length group of values or objects Access individual elements by index Use foreach to iterate over the array Use Length for one-dimensional arrays Use getLength() for rectangular

arrays Tip: Define constants for array lengths Tip: Define constants for initial values

Page 14: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Limitations of Arrays

Do you see any potential issues with using arrays?

Arrays can’t grow or shrink as needed

Page 15: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Collections Offer Flexibility Dynamically sized group of elements Better resource management Usually best choice for varying number

of elements

Page 16: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Different Kinds of Collections

List<T>Efficient sequential accessInefficient inserting into middle of list

SortedList<T>Access values by keyInefficient sequential accessEfficient inserting into middle of list

Queue<T> and Stack<T>Specialized access

Page 17: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Working with List<T>List<string> lastNames = new List<string>();lastNames.Add(“Smith”);lastNames.Add(“Barnes”);lastNames.Add(“Kelly”);lastNames.Add(“Metcalf”);

List<int> ages = new List<int>();ages.Add(43);ages.Add(24);ages.Add(31);ages.Add(27);ages.Add(“thirty-three”); // compile error – not int

lastNames.Sort(); // instance method for List<T>

Page 18: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Searching a List<T>

BinarySearch() requires Sort() BinarySearch() returns index or bitwise

complement of insertion point

lastNames.Sort();int index = lastNames.BinarySearch(“B”);

Page 19: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Working with SortedList<T>

// Create a collection of string values that we// can associate with int keys:

SortedList<int, string> classes = new SortedList<int, string>();

classes.Add(1006, “ASP.NET Fundamentals”);classes.Add(1007, “ASP.NET Advanced”);classes.Add(1002, “C#: Introduction for Developers”);classes.Add(1003, “Java Programming”);

// Access string value by int key:

string className = classes[1002];

Page 20: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Queues and Stacks

Queues and stacks define a strict ordering for how elements are added and removed

Queues are First-In-First-Out (FIFO)Like trains cars going through a tunnelThe tunnel is the queue and the cars are the

elements of the queueThe cars exit the tunnel in the same order

they entered the tunnel

Page 21: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Queues and Stacks

Stacks are Last-In-First-Out (LIFO)Like a shirts stacked in a drawerNew shirts go on top of the stackThe shirt on top is always the next one

removed from the stack Elements are discarded after retrieval

Page 22: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Count vs. Capacity

Capacity doubles when a collection outgrows its current capacity

Why might this be important to remember?

Set an initial capacity just above what you expect to use

Count = 11, Capacity = 16

Create a List<T> and add 13 elements

Page 23: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Untyped Collections

ArrayList is an untyped collection

// You can put any type of element into the array.

ArrayList list = new ArrayList();list.Add(5);list.Add(“Hello”);list.Add(4.3);

// But you need to cast it to the correct type when// removing it from the array.

int iValue = (int) list[0];string sValue = (string) list[1];decimal dValue = (decimal) list[2];

Page 24: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Choosing a Collection Class Raffle tickets Restaurant ordering system Track web site visitors over the last

seven days Online shopping cart Calculator

http://bit.ly/cs08-calc

Page 25: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Some Additional Collections Dictionary<TKey, TValue>

Unique keys NameValueCollection

Allows multiple values per key Hashtable BitArray, BitVector32

For working with bit flags LinkedList<T> Which collection should I use?

See http://bit.ly/cs08-selcol

Page 26: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Immutable Collections

.NET 4.5 contains the ImmutableList<T> class for use across threads

This…myList = myList.Add(anotherItem);

Instead of this…myList.Add(anotherItem);

Page 27: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Collection Exercise Create a new project in your folder on S: Create a form that will accept a name in a

TextBox Use a button to read the name and add it to

a list Create a Multiline, ReadOnly TextBox that

will display the list of names, sorted in alphabetical order

What input will be invalid? How will you handle invalid input?

Page 28: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

WORKING WITH DATES AND TIMES

Page 29: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

DateTime ObjectsDateTime when = new DateTime(2014, 1, 16, 18, 0, 0, 0);when = DateTime.Parse("2014-01-16T18:00:00-6:00");when = DateTime.Parse("2014-01-16 18:00:00");when = DateTime.Parse("Fri, 17 Jan 2014 00:00:00 GMT");when = DateTime.Parse("01/16/2014 6:00pm");when = DateTime.Parse("1/16/14 6pm");when = DateTime.Parse("Jan 16 2014");when = DateTime.Parse("6pm");

Stored internally as “ticks” since 01/01/01 00:00 1 tick = 100 nanoseconds We should be okay until ~2293 A.D.

Page 30: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

What time is it?

// Current date and timeDateTime now = DateTime.Now;

// Current date, 12:00AMDateTime today = DateTime.Today;

Page 31: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Displaying Date and TimeDateTime now = DateTime.Now;string text = now.ToLongDateString();text = now.ToShortDateString();text = now.ToLongTimeString();text = now.ToShortTimeString();

Date and time are formatted according to the operating system settings.

Page 32: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

DateTime Properties Date Month Day Year Hour Minute Second TimeOfDay DayOfWeek DayOfYear

Page 33: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Using DateTime Propertiesif ((myDoB.Month == yourDob.Month) && (myDob.Day == yourDob.Day)){ // What a happy coincidence!}

if ((today.DayOfWeek == DayOfWeek.Saturday) || (today.DayOfWeek == DayOfWeek.Sunday)){ Relax();}

Page 34: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

DateTime Methods

DaysInMonth(year, month) IsLeapYear(year)

Page 35: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Finding Relative Date and Time

DateTime expiration = DateTime.Now.AddDays(30); DateTime maturity = dob.AddYears(18); DateTime snooze = DateTime.Now.AddMinutes(5);

Add a negative value to subtract. These methods create a new DateTime object. The original

DateTime object is unchanged.

Page 36: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

TimeSpan ObjectsDateTime classTime = new DateTime(2014, 1, 16, 18, 0, 0);DateTime now = DateTime.Now;

TimeSpan freeTime = classTime – now;if (freeTime.TotalMinutes <= 0){ Panic();}if (freeTime.TotalMinutes <= 15){ Alert();}

Page 37: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Minutes vs. TotalMinutes

TimeSpan span = TimeSpan.FromMinutes(75);

// This is true...if (span.Minutes < 30){}

// This is false…if (span.TotalMinutes < 30){}

Page 38: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Date Exercise

Create a new project in your folder on S: Create a form that will accept date input

in a TextBox or DateTimePicker Create a Labels that will display the

number of years and days that have elapsed since a selected date

Did you get any unexpected results?

Page 39: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

WORKING WITH STRINGS

Page 40: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

What can we do with a string?

string alphabet = "abcdefghijklmnopqrstuvwxyz";

char m = alphabet[13];int letters = alphabet.Length;

foreach (char letter in alphabet){}

bool startsWell = alphabet.StartsWith("abc");bool endsWell = alphabet.EndsWith("xyz");

int x = alphabet.IndexOf("xyz");int x = alphabet.IndexOf('x');int x = alphabet.LastIndexOf('x');

Page 41: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Insert, Remove, and Replace

string alphabet = "abcdefghijklmnopqrstuvwxyz";

int l = alphabet.IndexOf("lmnop");string abbrev = alphabet.Remove(l, 5);string complete = abbrev.Insert(l, "lmnop");

string mixedCase = alphabet.Replace("abc", "ABC");

string beginning = alphabet.Substring(0, 6);string ending = alphabet.Substring(20);

Page 42: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Splitting Strings string numbers = "15,236,98,3,67";

string[] split = numbers.Split(',');

foreach (string number in split) { }

Page 43: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

UPATING THE FUTUREVALUE

EXAMPLE

Page 44: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Improved Input Handling

Update the example program to accept input that includes “$” and “%” if they occur in the appropriate location within the input data.

Look at example on p. 269. Oh, yeah…there’s also Trim(),

TrimStart(), and TrimEnd().

Page 45: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

StringBuilder Manipulating and modifying string objects

can be inefficient.

string objects are immutable newstring = oldstring.Insert(0, 5); newstring = oldstring.Substring(0, 5);

StringBuilder objects are mutable StringBuilder b = new StringBuilder(); b.Append("Hello."); b.Append("My Name is Neal."); string greeting = b.ToString();

Page 46: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Useful Here…string[] lotsOfStringParts;

string appended = "";foreach (string part in lotsOfStringParts){ appended += part;}

StringBuilder b = new StringBuilder();foreach (string part in lotsOfStringParts){ b.Append(part);}string appended = b.ToString();

Page 47: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Not Here…string firstName;string lastName;

string fullName = firstName + " " + lastName;

StringBuilder b = new StringBuilder();b.Append(firstName);b.Append(" ");b.Append(lastName);string fullName = b.ToString();

Page 48: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Formatting NumbersString.Format(formatStr, value1, value2, ...);

Ex. “Hello, my name is {0}.“ { index [ ,width ] [ :format [ ; negative_format [; zero_format ] ] ] }

Formats: c[x]: Currency to x decimal places d[x]: Integer containing x digits e[x]: Scientific notation to x decimal places f[x]: Decimal number to x decimal places g[x]: Most compact number format between e and f n[x]: Number with thousands separator to x decimal places p[x]: Percentage to x decimal places (multiplies by 100)

balance = String.Format("{0:$#,##0.00;($#,##0.00)}", val);

Page 49: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

Formatting DatesString.Format(formatStr, value1, value2, ...);

Formats: d: Short date D: Long date t: Short time T: Long time f: Long date, short time F: Long date, long time g: Short date, short time G: Short date, long time

balance = String.Format(“Date:{0:d} Time:{0:t}", DateTime.Now);

Page 50: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

String Exercise #1

Create a new project in your folder on S: Create a form that will accept a phone

number input in a TextBox Create a ReadOnly TextBox that will

display the phone number in a standard form (i.e. (xxx) xxx-xxxx or xxx-xxx-xxxx)

What input will be invalid? How will you handle invalid input?

Page 51: What is an array? int string decimal int string decimal int string decimal int decimal “Elements” in the array We can declare variables for individual

String Exercise #2

Create a new project in your folder on S: Create a form that will accept a

sequence of numbers in a TextBox Create a Multiline, ReadOnly TextBox

that will display the list of numbers, sorted from smallest to largest

What input will be invalid? How will you handle invalid input?