80 likes | 216 Views
Array Lists. pg. 234-239. Arrays in C#. Can set size at run time (as in C++) int actualSize = …; Emp [ ] staff = new Emp [actualSize]; Does not completely resolve problem of dynamically modifying arrays – once array size is set, cannot change easily. ArrayList class in C#.
E N D
Array Lists pg. 234-239
Arrays in C# • Can set size at run time (as in C++) int actualSize = …; Emp [ ] staff = new Emp [actualSize]; • Does not completely resolve problem of dynamically modifying arrays – once array size is set, cannot change easily.
ArrayList class in C# • Untyped collections defined in System.Collections package • Typed collections in System.Collections.Generic package • Shrink and grow dynamically • Lower bound is 0 • Holds references to objects • Need to cast whenever you take an item out of an typed array list
add Method ArrayList staff = new ArrayList( ); staff.add (new Emp ( …) ); staff.add (new Emp (…) ); • ArrayList class manages internal array of object references. • When it gets full, then the array list automatically creates a bigger array and copies objects in smaller array to bigger array.
Size stuff • Returns actual number of elements in array list staff.Count • When you know it has reached permanent size staff.TrimToSize ( );
Accessing Array List elements • To get ith element (object),: staff [i] • To get ith element (if typed) , must cast employee e = (Emp) staff [ i];
ArrayList Trick • Flexible growth and convenient element access • First make an array list and add elements ArrayList list = new ArrayList ( ); while ( …) { x = …; list.add (x); } • Then use ToArray method to copy elements into array.
ArrayList Trick • Then use ToArray method to copy elements into array (untyped) int[] a = (int[]) list.ToArray(typeof(int)); • Other convenient methods • Contains (object) • BinarySearch (object) • Sort( )