90 likes | 189 Views
Learn how to create arrays of objects and collections in complex programs. Objects within collections can be accessed individually using the collection-name[index] notation.
E N D
Arrays How to create an array of objects
Collections • Writing complex programs using named variables would be impossible • Most objects never yet named. Instead, they are created and placed in collections • Collections are just objects that can hold references to other objects • Objects within collections can be accessed individually • collection-name[index] notation often used
Nature of Object Collection Collection Object Objects in Memory Implication: The objects and collection objects must be created separately
Nature of Value Type Collection Implication: The collection array actually holds the values. For example: int[] myVals = new int[8]; myVals[0]=17; myVals[1]=23; myVals[2]=9; myVals[3]=5; myVals[4]=101; myVals[5]=2; 17 23 9 5 101 2 0 0 Collection Object
Array collection • Collection of specific objects • Object array can hold anything in C# • Defined to be a specific size • Determined upon construction • Can’t be changed • Provides useful properties • [index] to get individual elements (e.g., MyArray[0] is 1st, MyArray[1] is 2nd, etc.) • Length gives number of elements
Declaring Array Basic format: ObjectType[] variableName1 = {element-list}; // Creates collection & elements ObjectType[] variableName2 = new ObjectType[integer-val]; // Creates collection ObjectType[] variableName3; // This array == null until initialized Examples:
Iterating through an Array • Comments: • The Length property returns how many characters there are in an array • i < myData.Length reflects the fact that array coefficients go from 0 to Length-1
Example: Point array in Ism4300 • Comments (based on highlighting): • Yellow: An array member variable is declared • Green: The 9 element collection object is created • Light Blue: The individual objects in the collection are created
Parting words… • In earlier languages (e.g., FORTRAN, C, COBOL), the array was the only built-in collection • Still useful—although the lack of resizing ability is a limitation • Other collection classes—most notably the generic classes—are more flexible • Resizing • Ordering and lookup