Friday, 2 November 2007

Chapter 4, lesson1: Collecting Data Items.

  • collections - classes used for grouping, managing, iterating over related objects.
  • challenge - to discern the right colln to use in a specific situation.

ArrayList

  • A simple, resizeable, unordered, index-based colln of objs of any type.
  • adding/removing items - designed for these operations.
  • adding - can add objects that exist as variabls, created inline, and even value types. Value types will implicitly firstly be wrapped in a obj ref. - i.e. boxed.
  • AddRange - adding from an array or another collection. Supports adding a range of items from any object that supports ICollection interface.
  • Add/AddRange - add to end of ArrayList.
  • Insert/InsertRange - insert at specific positions.
  • Use Indexer to set at a position - however not same as Insert - it overwrites.
  • Remove, RemoveRange, RemoveAt.
  • Contains, IndexOf, Clear - if Contains(myString), then IndexOf(myString), RemoveAt(index) else Clear().

ArrayList - iterating

There are several mths to iterate over items in an ArrayList.

  • numeric indexer - for x = 0 to colln.Count - colln[x]
  • IEnumerable - ArrayList supports this interface which allows use of Enumerator to access list - GetEnumerator() returns an IEnumerator interface, which provides mechanism - MoveNext() - for iterating in fwd direction.
  • IEnumerator - colln.GetEnumerator(); while(enum.MoveNext()) - enum.Current;
  • foreach - enumerates a colln. Can be used on any colln that support IEnumerable.

Interfaces in Collections

  • ICollection - derived from IEnumerable - implemented in the API of most colln classes.
  • ICollection.CopyTo - easy way to copy contents -> Array.
  • IList - derived from ICollection - exposes mthds to get at items.

Sorting - colln.Sort();

  • Sort works by using Comparer class to perform comparison.
  • Comparer class - default implementation that supports IComparer interface.
  • IComparer - impl. Compare() - takes 2 objs & returns an int that represents the result.
  • Sort - allows one to specify diff obj which implements IComparer.
  • No comments: