Session 4
Session 4
PROGRAMMING II
Slide 2
Collections cont’d
• For some collections, you can assign a key to any
object that you put into the collection so that you
can quickly retrieve the object by using the key
• A collection is a class, so you must declare an
instance of the class before you can add elements to
that collection.
• If your collection contains elements of only one data
type, you can use one of the classes in the
System.Collections.Generic namespace
Slide 3
Kinds of Collections
• Many common collections are provided by .NET.
• Each type of collection is designed for a specific
purpose.
• The kinds are:
– System.Collections.Generic classes
– System.Collections.Concurrent classes
– System.Collections classes
• We focus on only System.Collections.Generic and
System.Collections classes
Slide 4
System.Collections Classes
• The classes in the System.Collections namespace do
not store elements as specifically typed objects, but
as objects of type Object.
• The following table lists some of the frequently used
classes in the System.Collections namespace:
Slide 5
ArrayList Class
• Implements the IList interface using an array whose
size is dynamically increased as required.
• The ArrayList is not guaranteed to be sorted. You
must sort the ArrayList by calling its Sort method
prior to performing operations (such as
BinarySearch) that require the ArrayList to be sorted
• Not recommended that you use the ArrayList class
for new development, it does not always offer the
best performance, use the generic List<T> class.
Slide 6
ArrayList Example
ArrayList myAL = new ArrayList();
myAL.Add("Hello");
myAL.Add("World");
myAL.Add("!");
Slide 7
Hashtable Class
• Represents a collection of key/value pairs that are
organized based on the hash code of the key.
• Each element is a key/value pair stored in a DictionaryEntry
object
• When an element is added to the Hashtable, the element is
placed into a bucket based on the hash code of the key.
• Subsequent lookups of the key use the hash code of the key
to search in only one particular bucket, reducing the
number of key comparisons required to find an element.
• Hashtable class not recommended for new development,
use the generic Dictionary<TKey,TValue> class.
Slide 8
Hashtable Example
Hashtable myhashTable = new Hashtable();
myhashTable.Add("txt", "notepad.exe");
myhashTable.Add("bmp", "paint.exe");
Slide 9
Queue Class
• Represents a first-in, first-out collection of objects.
• This class implements a queue as a circular array.
• Objects stored in a Queue are inserted at one end and
removed from the other.
• Three main operations can be performed on a Queue and its
elements:
• Enqueue adds an element to the end of the Queue.
• Dequeue removes the oldest element from the start of the Queue.
• Peek peek returns the oldest element that is at the start of the
Queue but does not remove it from the Queue
• Queue not recommended for new development, use
Queue<T>
Slide 10
Stack Class
• Represents a simple last-in-first-out (LIFO) non-
generic collection of objects.
• Three main operations can be performed on a Stack
and its elements:
• Push inserts an element at the top of the Stack.
• Pop removes an element from the top of the Stack.
• Peek returns an element that is at the top of the
Stack but does not remove it from the Stack.
• Not recommended for new development, use
Stack<T>
Slide 11
Stack Example
Stack myStack = new Stack();
myStack.Push("Hello");
myStack.Push("World");
myStack.Push(123);
myStack.Push(true);
Console.WriteLine( "\tCount: {0}",
myStack.Count );
Slide 12
Why Non-generic Collections should be
Avoided
• Error prone: since non-generic collections are
untyped, it requires frequent casting between object
and the actual type you're expecting.
– Since the compiler can't check that your types are
consistent, it's easier to put the wrong type in the wrong
collection.
• Less performant: generic collections have the
advantage that value types don't have to be boxed as
object.
Slide 13
Non-Generic Collection Types Replacement
Slide 14
Generics
• Generics let you tailor a method, class, structure, or
interface to the precise data type it acts upon
• Among the benefits of generics are increased code
reusability and type safety.
• Generics are classes, structures, interfaces, and
methods that have placeholders (type parameters)
for one or more of the types that they store or use.
• A generic collection class might use a type parameter
as a placeholder for the type of objects that it stores.
Slide 15
Generics cont’d
• The type parameters appear as the types of its fields and the parameter
types of its methods
• A generic method might use its type parameter as the type of its return
value or as the type of one of its formal parameters.
• When you create an instance of a generic class, you specify the actual
types to substitute for the type parameters.
Slide 17
Generic Method
T GenMethod<T>(T arg) T NonGenMethod(T arg) {
{ T temp = arg;
T temp = arg; //...
//... return temp;
return temp; }
}
Slide 18
Advantages
• Type safety. Generics shift the burden of type safety
from you to the compiler.
– There is no need to write code to test for the correct data
type because it is enforced at compile time.
– The need for type casting and the possibility of run-time
errors are reduced.
• Less code and code is more easily reused.
• Better performance.
– Generic collection types generally perform better for
storing and manipulating value types because there is no
need to box the value types.
Slide 19
Limitations
• Enumerations cannot have generic type parameters.
• Lightweight dynamic methods cannot be generic.
• A nested type that is enclosed in a generic type
cannot be instantiated unless types have been
assigned to the type parameters of all enclosing
types
Slide 20
System.Collections.Generic Classes
• A generic collection is useful when every item in the collection has the
same data type.
• A generic collection enforces strong typing by allowing only the desired
data type to be added.
• Below is a list of frequently used classes.
Slide 21
Dictionary<TKey,TValue> Class
• Represents a collection of keys and values.
• Tkey: The type of the keys in the dictionary.
• Tvalue: The type of the values in the dictionary
• There also exists assorted version of Dictionary (SortedDictionary<Tkey,TValue>)
Slide 22
List<T> Class
• Represents a strongly typed list of objects that can be accessed by
index.
• Provides methods to search, sort, and manipulate lists.
• Not sorted by default.
List<string> names = new List<string>();
names.Add(”Peter");
names.Add(”Paul");
names.Sort();
names.Reverse();
Names.BinarySearch(“Peter”);
names.Remove(”Peter");
names.Clear();
Slide 23
Queue<T> Class
• This class implements a generic queue as a circular
array.
• Objects stored in a Queue<T> are inserted at one end
and removed from the other.
• Queues and stacks are useful when you need
temporary storage for information; that is, when you
might want to discard an element after retrieving its
value.
• Use Queue<T> if you need to access the information
in the same order that it is stored in the collection
Slide 24
Queue<T> Class
• Three main operations can be performed on a
Queue<T> and its elements:
• Enqueue adds an element to the end of the Queue<T>.
• Dequeue removes the oldest element from the start of the
Queue<T>.
• Peek peek returns the oldest element that is at the start of
the Queue<T> but does not remove it from the Queue<T>
Slide 25
Queue<T> Class
Queue<string> nums = new Queue<string>();
nums.Enqueue("one");
nums.Enqueue("two");
nums.Enqueue("three");
Console.WriteLine(
"\nDequeuing '{0}’”, nums.Dequeue()
);
Console.WriteLine(
"Peek at next item to dequeue: {0}", nums.Peek()
);
Console.WriteLine("Dequeuing '{0}'", nums.Dequeue());
Console.WriteLine(”Count '{0}'", nums.Count);
nums.Clear();
Console.WriteLine(”Count '{0}'", nums.Count);
Slide 26
SortedList<TKey,TValue> Class
• Represents a collection of key/value pairs that are
sorted by key based on the associated IComparer<T>
implementation.
• SortedList<TKey,TValue> is implemented as an array
of key/value pairs, sorted by the key. Each element
can be retrieved as a KeyValuePair<TKey,TValue>
object.
• SortedList<TKey,TValue> requires a comparer
implementation to sort and to perform comparisons.
•
Slide 27
SortedList<TKey,TValue> Class
SortedList<string, string> myList =
new SortedList <string, string>();
Slide 28
Stack<T> Class
• Represents a variable size last-in-first-out (LIFO)
collection of instances of the same specified type.
• Stack<T> is implemented as an array.
• Stacks and queues are useful when you need
temporary storage for information; that is, when you
might want to discard an element after retrieving its
value.
• Use Stack<T> if you need to access the information
in reverse order.
Slide 29
Stack<T> Class cont’d
• Three main operations can be performed on a
Stack<T> and its elements:
• Push inserts an element at the top of the Stack<T>.
• Pop removes an element from the top of the
Stack<T>.
• Peek returns an element that is at the top of the
Stack<T> but does not remove it from the Stack<T>.
Slide 30
Stack<T> Class cont’d
Stack<string> numbers = new Stack<string>();
numbers.Push("one");
numbers.Push("two");
numbers.Push("three");
numbers.Clear();
Slide 31
THE END
• Assignments on SAKAI
Slide 32