Chapter 27 Collections - PowerPoint PPT Presentation

1 / 21
About This Presentation
Title:

Chapter 27 Collections

Description:

... to a target type, as long as the number of dimensions is ... Except IHashCodeProvider is not obsolete (.NET 2.0) The documentation for Collections is at: ... – PowerPoint PPT presentation

Number of Views:33
Avg rating:3.0/5.0
Slides: 22
Provided by: beiz
Category:

less

Transcript and Presenter's Notes

Title: Chapter 27 Collections


1
Chapter 27Collections
2
.NET Containers
  • There are two name spaces in the FCL where
    containers are defined
  • System.Array (class)
  • Provides methods for creating, manipulating,
    searching, and sorting arrays
  • System.Collections (namespace) contains
  • Interfaces and classes that define various
    collections of objects, such as lists, queues,
    bit arrays, hash tables and dictionaries

3
Arrays
  • Arrays are derived from System.Array. This class
    implements the interfaces ICloneable,
    IEnumerable, ICollection and IList.
  • The members of System.Array can be also found in
    the MSDN documentation
  • http//msdn2.microsoft.com/en-us/library/system.ar
    ray_members(vs.80).aspx
  • Note that there are 7 properties, 35 (public)
    methods, 2 protected methods, and 9 explicit
    interface (method) implementations

4
Arrays
  • Arrays can contain value types or reference
    types.
  • The contents are stored contiguously
  • All elements must be of the same type
  • All elements can be directly accessed
  • Common operations are
  • Declaration
  • Allocation of memory (size)
  • Access of elements
  • Resize (?)

5
Array Casting
  • Arrays that contain reference types can be
    implicitly cast to a target type, as long as the
    number of dimensions is the same
  • FileStream , fs2dim new FileStream5,10
  • Object , o2dim fs2dim
  • Arrays that contain value types cant be cast to
    other types
  • Int32 ildim new Int325
  • Object oldim (Object) ildim//compiler
    error
  • Array.Copy can be used to create that effect
  • Object oldim new Object ildim.Lenght
  • Array.Copy(ildim, oldim, ildim.Lenght) // ildim
    -gt oldim
  • Copy (sourceArray, destinationArray, length)
  • Array.Copy can convert elements in the array as
    required.
  • Just remember that, by definition, copies of
    reference types are shallow

6
Using CopyTo to Resize an Array
  • Copies all the elements of the current
    one-dimensional Array to the specified
    one-dimensional Array starting at the specified
    destination Array index.
  • using System
  • using System.Collections
  • public class Redimensioning
  • public static void Main()
  • // Create an integer array with three
    elements
  • int fib new int3
  • fib0 1
  • fib1 1
  • fib2 2
  • // Redimension message to a 10 element
    array
  • int temp new int10
  • // Copy the fib array to temp
  • fib.CopyTo(temp, 0)
  • // Assign temp to fib
  • fib temp

7
Take home quiz
  • Write a general purpose ReSize array method
  • public static Array ReSize(Array oldArray, int
    newSize)
  • ///Your code comes here
  • You will need to look at the Array members on the
    msdn.

8
System.Collections
  • The namespace System.Collections is part of the
    FCL, which is located in mscorlib.dll.
  • This name space defines 12 classes, 9 interfaces
    and one structure.
  • The important classes are ArrayList, BitArray,
    CollectionBase, Hashtable, Queue,
    ReadOnlyCollectionBase, SortedList, Stack.
  • All Interfaces are important. Except
    IHashCodeProvider is not obsolete (.NET 2.0)
  • The documentation for Collections is at
  • http//msdn2.microsoft.com/en-us/library/system.co
    llections.aspx

9
System.Collections.ArrayList
  • ArrayList is a class that implements the IList
    interface.
  • ArrayLists have the following desirable
    properties
  • Can grow or shrink as necessary
  • Can contain mixtures of types, including other
    ArrayLists
  • Elements can be accessed using indexing notations
  • ArrayList al new ArrayList()
  • al.Add(5)
  • al.Add(4)
  • al.Add(3)
  • al.Add(2)
  • al.Add(1)
  • al.Add("String")
  • al.Add(new ArrayList() )
  • a12//Returns object, you need to cast

10
The Need for Casting
  • Internally, ArrayLists store elements as
    reference types, even if the original elements
    were value types.
  • In fact, since the argument to ArrayList.Add (
    object o ) is of type object value types are
    boxed. Therefore getting elements from the array
    must be cast to the original type
  • ArrayList al new ArrayList()
  • al.Add(5)
  • al.Add(4)
  • al.Add(3)
  • al.Add(2)
  • al.Add(1)
  • al.Add("String")
  • al.Add(new ArrayList() )
  • // Read access
  • int x (int) al0
  • string y (string) al5
  • // Write access
  • al1 5
  • // ArgumentOutOfRange EXCEPTION
  • al7 5

11
Boxing Unboxing
  • Boxing Converting a value type to reference type
  • Boxing may done implicitly
  • Unboxing just the opposite
  • Has to be done explicitly
  • class Test
  • static void Main()
  • int i 1
  • object o i // boxing
  • int j (int)o // unboxing

12
(No Transcript)
13
(No Transcript)
14
(No Transcript)
15
Working with ArrayLists
  • using System
  • using System.Collections
  • public class JobProcessing
  • private static ArrayList jobs new
    ArrayList()
  • private static int nextJobPos 0
  • public static void AddJob(string jobName)
  • jobs.Add(jobName)
  • public static string GetNextJob()
  • if (nextJobPos gt jobs.Count - 1)
  • return "NO JOBS IN BUFFER"
  • else
  • string jobName (string)jobsnextJobP
    os
  • nextJobPos
  • return jobName

The code in the right uses ArrayList to implement
a first come, first served job scheduling data
structure Executing the code we get 1 23 NO JOBS
IN BUFFER NO JOBS IN BUFFER 4 Is this an
efficient solution ?
16
Working with ArrayLists
  • Is this an efficient solution ? NO! The array
    continues growing every time a new job entry is
    added.
  • This problem could be fixed by creating a
    circular array. The key is to have a starting
    position, an end position, and a size. AddJob
    could use a method to increment the position and
    ensure that it is never greater than a certain
    size
  • int increment(int variable)
  • return (variable 1) theArray.Length

17
System.Collections.Queue
  • The Queue is a collection class that provides
    FIFO functionality.
  • The method Enqueue admits elements at the tail of
    the queue and the method Dequeue expels elements
    at the head of the queue.
  • The method Peek returns the element at the head
    without removing it from the queue.
  • Count returns the number of elements in the queue
  • Clear removes all objects
  • Clone creates a shallow copy
  • CopyTo copies the elements into an existing
    onedimensional Array.
  • Other methods include GetType, Equals, Contains,
    ToArray, TrimToSize, ToString, GetEnumerator. . .

18
System.Collections.Stack
  • The Stack is a collection that provides LIFO
    functionality.
  • Push is a method that inserts an element into the
    top of the stack.
  • Pop removes the element at the top of the stack.
  • The methods Count, Clear, Clone, Contains,
    CopyTo, Equals, GetEnumerator, Peek, ToArray,
    ToString, etc. have the same functionality as
    described for the base class.

19
System.Collections.Hashtable
  • Hash tables are data structures that store pairs
    of key/values in slots, called buckets.
  • The main quality of hash tables is that search
    (lookup) is very fast because the hard work is
    done during the storage phase. In essence, a
    unique key is obtained to store values in the
    buckets.
  • The kind of code that is used with HashTables
    includes
  • HashTable aTable new HashTable( )
  • aTable.Add("Sunday", "Domingo") // (key,value)
    pair
  • aTable"Monday" "Lunes" // tableKeyvalue
  • foreach (DictionaryEntry entry in table)
  • Console.Write("Key0, Value0\n", entry.Key,
    Entry.Value)
  • aTable.Remove( key) aTable.Clear()
    aTable.Count() and many others.

20
System.Collections.Hashtable
  • using System
  • using System.Collections
  • public class HashtableDemo
  • private static Hashtable ages new
    Hashtable()
  • public static void Main()
  • // Add some values to the Hashtable,
    indexed by a string key
  • ages.Add("Matt", 25)
  • ages.Add("Jon", 6)
  • ages.Add("Kevin", 25)
  • // Access a particular key
  • if (ages.ContainsKey("Jon"))
  • int nAge (int)ages"Jon"
  • Console.WriteLine("Jon is "
    nAge.ToString())
  • else
  • Console.WriteLine("Jon is not in the
    hash table...")

21
System.Collections.Hashtable
  • Since Hashtable.Keys is a collection (of keys)
    code as below can be used
  • foreach( string key in ages.Keys )
  • Console.WriteLine(age ageskey.ToString())
  • Other methods include GetHash(key) GetHashCode(),
    which can be used to tune and improve the
    efficiency of the tables.
Write a Comment
User Comments (0)
About PowerShow.com