Lecture 10 Collections Richard Gesick Objectives • The nongeneric and generic collections that are provided by the .NET Framework. • To use class Array’s static.

Download Report

Transcript Lecture 10 Collections Richard Gesick Objectives • The nongeneric and generic collections that are provided by the .NET Framework. • To use class Array’s static.

Lecture 10
Collections
Richard Gesick
Objectives
• The nongeneric and generic collections that are provided by
the .NET Framework.
• To use class Array’s static methods to manipulate arrays.
• To use the foreach statement with the .NET collections.
• To use nongeneric collection classes ArrayList
• To use generic collection class List<T>
Introduction
•
•
•
•
•
For the vast majority of applications, there is no need to
build custom data structures.
Instead, you can use the prepackaged data-structure
classes provided by the .NET Framework.
These classes are known as collection classes—they
store collections of data. Each instance of one of these
classes is a collection of items.
Collection classes enable programmers to store sets of
items by using existing data structures, without concern
for how they are implemented.
Programmers can code faster and expect excellent
performance, maximizing execution speed and
minimizing memory consumption.
Intro (2)
• The .NET Framework provides three namespaces
dedicated to collections:
• System.Collections contains collections that store
references to objects.
• Most new applications should use the collections in
the System.Collections.Generic namespace, which
contains generic collection classes.
• The System.Collections.Specialized namespace
contains several collections that support specific
types, such as strings and bits.
Intro (3)
• The collections in these namespaces
provide standardized, reusable
components; you do not need to write
your own collection classes.
• These collections are written for broad
reuse and tuned for rapid execution and
for efficient use of memory.
Arrays
• Arrays are good for fast/immediate access to the
data, but their limitation is that they are fixed in
size. To overcome this, collections that are
dynamic allow us to grow/shrink the data
structure.
• High-level APIs provide a means to access these
dynamic collections similar to arrays (and use the
[] index notation), but realize that there is a lot of
memory management that is happening behind
the scenes.
Arrays(2)
• All arrays implicitly inherit from abstract base
class Array (namespace System).
• Class Array defines property Length, which
specifies the number of elements in the array.
• In addition, class Array provides static
methods that provide algorithms for processing
arrays. Many of these methods have several
overloaded versions.
Static Methods of Arrays
• When Array method Sort returns, the array contains its
original elements in ascending order.
int[ ] dblValues = { 3, 54,12, 3, 45, 78, 65};
Array.Sort(dblValues);
• Use Array method Copy to copy elements from one array
to another.
• The first argument is the array to copy.
• The second argument is the destination array.
• The third argument is an int representing the number
of elements to copy.
Array.Copy(dblValues,ddblCopy,dblValues.Length);
Static Methods of Arrays(2)
• Array method BinarySearch performs a binary search
on a sorted array.
• Method BinarySearch receives the sorted array in
which to search and the key for which to search.
int result = Array.BinarySearch(dblValues,6);
• The method returns the index in the array at which it
finds the key, or a negative number if the key was not
found.
• Its behavior on an unsorted array is unpredictable.
Other static Array methods include:
Clear
sets a range of elements to 0, false or null.
CreateInstance creates a new array of a specified type.
IndexOf
locates the first occurrence of an object in
an array or portion of an array.
LastIndexOf
locates the last occurrence of an object in
an array or portion of an array.
Reverse
reverses the contents of an array or portion
of an array.
ArrayList
• Many languages provide a means to manage
polymorphic collections such as the ArrayList
• This is polymorphic in that it holds elements of type
"object", and all classes implicitly inherit from
"object".
• This is what provides the "Equals()", "ToString()",
etc. methods that all things have.
ArrayList (2)
ArrayList collection = new ArrayList();
collection.Add(42);
collection.Add("Dog");
collection.Add(new Vector2(5,7));
This is permissible because the int, string, and
Vector2 class are all instances of the "object" class
(via inheritance).
ArrayList(3)
The problem with the ArrayList (and any polymorphic
collection) is that you must be careful in handling the
data when you access it.
You could not, for example do something like this (since
all elements may not be ints):
foreach(int i in collection)
{
// do something
}
This may generate an invalid typecast exception.
Array
List
Meth
-ods
Add
Adds an object to the ArrayList and returns an int specifying
the index at which the object was added.
Capacity
Property that gets and sets the number of elements for which space is
currently reserved in the ArrayList.
Description
Method or
property
Clear
Removes all the elements from the ArrayList.
Contains
Returns true if the specified object is in the ArrayList;
otherwise, returns false.
Count
Read-only property that gets the number of elements stored in the
ArrayList.
IndexOf
Returns the index of the first occurrence of the specified object in the
ArrayList.
Insert
Inserts an object at the specified index.
Remove
Removes the first occurrence of the specified object.
RemoveAt
Removes an object at the specified index.
RemoveRange
Removes a specified number of elements starting at a specified index in
the ArrayList.
Sort
Sorts the ArrayList.
TrimToSize
Sets the Capacity of the ArrayList to the number of elements the
ArrayList currently contains (Count).
Generic or Parameterized Collections
• To overcome the limitations of polymorphic
collections, modern languages also provide a means
by which you can explicitly state the type of thing you
want the collection to manage.
• You do this via a "parameter" to the class when you
define it.
• List<T> is called a generic class because it can be
used with any type of object.
• T is a placeholder for the type of the objects stored
in the list.
List
• The Add method appends its argument to the
end of the List.
• The Insert method inserts a new element
at the specified position.
• The first argument is an index—as with arrays,
collection indices start at zero.
• The second argument is the value that is to be
inserted at the specified index.
• All elements at the specified index and above are
shifted up by one position.
List
• The Count property returns the number of elements
currently in the List.
• Lists can be indexed like arrays by placing the index
in square brackets after the List variable’s name.
• The Remove method is used to remove the first
instance of an element with a specific value.
• If no such element is in the List, Remove does nothing.
• RemoveAt removes the element at the specified
index; all elements above that index are shifted down
by one.
List
• The Contains method returns true if the element is found in
the List, and false otherwise.
• Contains compares its argument to each element of the
List in order, so using Contains on a large List is inefficient.
• The Capacity property indicates how many items the List can
hold without growing.
• List is implemented using an array behind the scenes. When
the List grows, it must create a larger internal array and copy
each element to the new array.
• A List grows only when an element is added and there is no
space for the new element.
• The List doubles its Capacity each time it grows.
Using List
List<int> numbers = new List<int>();
numbers.Add(42);
numbers.Add(9);
Since the type that the collection holds is known, we
can do something like this:
foreach(int i in numbers)
{
Console.WriteLine(i);
}
And you can also access the elements via the [] index
notation as in:
numbers[0] = 8;