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

Post on 02-Jan-2016

274 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

ARRAYS AND COLLECTIONS

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.

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…

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.

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?

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?

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

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.

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

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

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

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

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

Limitations of Arrays

Do you see any potential issues with using arrays?

Arrays can’t grow or shrink as needed

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

of elements

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

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>

Searching a List<T>

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

complement of insertion point

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

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

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

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

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

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

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

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

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

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?

WORKING WITH DATES AND TIMES

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.

What time is it?

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

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

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.

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

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

DateTime Methods

DaysInMonth(year, month) IsLeapYear(year)

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.

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

Minutes vs. TotalMinutes

TimeSpan span = TimeSpan.FromMinutes(75);

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

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

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?

WORKING WITH STRINGS

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

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

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

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

foreach (string number in split) { }

UPATING THE FUTUREVALUE

EXAMPLE

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().

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

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

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

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

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

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?

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?

top related