Sei sulla pagina 1di 25

Collections

Collections are generic data structures for containing objects or primitives These are often in the form of common data structures like lists, and dictionaries Many of the collections have interfaces representing their functionality

The IEnumerable Interface


This states that the class supports an enumerator or iterator which steps through the elements one-by-one Classes which implement this interface can be used with the foreach statement public interface IEnumerable { IEnumerator GetEnumerator(); }

The IEnumerator Interface

This is the interface the enumerator must implement It is usually implemented as a private class within the class being enumerated

public interface IEnumerator { bool MoveNext(); bool Reset(); object Current { get; } }

IndexedArrayEnumerator
private class IndexedArrayEnumerator: IEnumerator int idx; IndexedArray theArray; public IndexedArrayEnumerator(IndexedArray ar) theArray = ar; idx = -1; } public bool MoveNext() { idx++; if(idx >= theArray.data.Length) return false; else return true; } public void Reset() idx = -1; } { { {

public object Current { get{ return theArray[idx]; } } }

Getting an Enumerator
public IEnumerator GetEnumerator() { return new IndexedArrayEnumerator(this); }

This creates and returns an enumerator Using a separate enumerator class allows several enumerators to operate at the same time

The ICollection Interface


Defines properties and methods for all collections Implements: IEnumerable

Count

the number of elements in the collection

CopyTo(Array

ar, int idx)

Copies all elements to an array starting at the index

ArrayLists
The problem with arrays is their fixed size ArrayLists fix this by resizing the array when the addition of new members exceeds the capacity The class has an extensive set of methods

ArrayList Methods
Method/Property
Capacity Item() Add()

Description
The number of elements the list can hold Indexer Add an object to the ArrayList

AddRange()
BinarySearch() Clear()

Add the elements of a collection to the end of the array


Binary search Removes all elements from the ArrayList

Clone() Contains()
CopyTo()

Creates a shallow copy Determines if a value is in the ArrayList


Copies to a 1-D array

ArrayList Methods
Method/Property
GetEnumerator() GetRange() IndexOf()

Description
Returns an enumerator Copies a range to a new ArrayList Returns the index of the first occurrence of a value

InsertRange()
Remove() RemoveAt()

Inserts elements from a collection


Removes the first occurrence of an element Removes the element as a specific location

Sort() ToArray()
TrimToSize()

Sorts the ArrayList Copies the elements to a new array


Sets capacity to current size

Sorting
Sorting primitives is easy since comparing one to another is well-defined Sorting user-defined types is more difficult since you do not know how to compare one to another There are two solutions

IComparable
IComparer

The IComparable Interface

This require one method CompareTo which returns


-1 if the first value is less than the second 0 if the values are equal 1 if the first value is greater than the second

This is a member of the class and compares this to an instance passed as a parameter public interface IComparable { int CompareTo(object obj) }

The IComparer Interface

This is similar to IComparable but is designed to be implemented in a class outside the class whose instances are being compared Compare() works just like CompareTo()

public interface IComparer { int Compare(object o1, object o2); }

Sorting an ArrayList

To use CompareTo() of IComparable


ArrayList.Sort()

To use a custom comparer object


ArrayList.Sort(IComparer

cmp)

To sort a range
ArrayList.Sort(int

start, int len,

IComparer cmp)

Implementing IComparer

To sort people based on age

class PersonComparer: IComparer { public int Compare(object o1, object o2) { PersonBase p1 = (PersonBase)o1; PersonBase p2 = (PersonBase)o2; return p1.Age.CompareTo(p2.Age); } }

ICloneable Interface

This guarantees that a class can be cloned The Clone method can be implemented to make a shallow or deep clone

public interface ICloneable { object Clone(); }

Queue Class
Implements: ICollection, IComparable, ICloneable

Method Enqueue(object)

Description Adds an object to the queue

object Dequeue()
object Peek() object[] ToArray()

Takes an object off the queue and returns it. Throws InvalidOperationException if empty.
Returns object at head of queue without removing it. Returns contents as an array.

Stack Class
Implements: ICollection, IComparable, ICloneable

Method

Description

Push(object)
object Pop()

Adds an object to the stack


Takes an object off the stack and returns it. Throws InvalidOperationException if empty.

object Peek()
object[] ToArray()

Returns object at top of stack without removing it.


Returns contents as an array.

IDictionary Interface
A dictionary is an associative array It associates a key with a value and allows a value to be retrieved by providing the key Implements: ICollection, IEnumerable

IDictionary Interface
Method/Property Add(object key, object value) Remove(object key) bool Contains(object key)
IDictionaryEnumerator GetEnumerator() object this[object key] ICollection Values ICollection Keys

Description Adds a key and value to the collection Removes the key and value pair True if the dictionary contains the key
Returns an enumerator Gets or sets item with specified key. If the key does not exist, it is created. Returns the values as a collection Returns the keys as a collection

Hashtables
The hashtable is a common implementation of the IDictionary interface If the key is not an integer then the hashcode for the key is used as an index into the hashtable Keys used with hashtables must have unique hashcode for every value

IDictionaryEnumerator Interface
This is the type of enumerator used with dictionaries It implements IEnumerator Has properties

Key

Returns the key for the item Returns the value for the item

Value

BitArray Class
Long bit strings can be difficult to store efficiently Since data structures can be addressed on the byte level, we end up storing one bit per byte, wasting 7 bits The BitArray class stores the bits efficiently while providing access

BitArray Class

The constructor is overloaded


BitArray(Boolean[]) Makes a BitArray from an array of Booleans BitArray(Byte[]) Makes an array from an array of Bytes where each byte represents 8 bits BitArray(int len) Creates a BitArray of len bytes BitArray(int[]) Makes a BitArray from the 32 bits in each int in an array of ints

BitArray Indexer

The BitArray has an indexer providing both get and set


BitSet bs = new BitSet(8); bs[0] = true; Console.WriteLine(bs[1]);

There are also Get and Set methods


bool Get(int index) void Set(int index, bool value)

BitArray Operations

Various Boolean operations are provided


BitArray

And(BitArray) BitArray Or(BitArray) BitArray Xor(BitArray) BitArray Not()

You can set all of the bits at once


void

SetAll(bool value)

Potrebbero piacerti anche