Lecture Set 9 Arrays, Collections, and Repetition Part D – Repetition and Collections
Objectives To learn how to store and manage “repeating data items” (such as multiple payroll records) We sometimes call these repeating items a list C# implements lists as collections Use generic collections of objects to locate items in a list and to add, change, and delete list items These are operations that we can perform on a Visual Basic collection Use controls that operate on lists, including the ListBox and ComboBox controls Use the DataGridView control to work with tabular data
Introduction to Collections Collections are stores of repeating items All collections store references to objects having the same data type or different data types – even here there is some commonality We will look at the “different data types” situation briefly and revisit it when we examine inheritance Some collections are predefined The Controls collection, for example It is possible to create custom collections BUT – how do these differ from arrays?
Arrays versus Collections
Creating Collections (more examples)
More Examples
Still More Examples (values taken from previous slide)
Quick Method for Message Box Displays
Applying Methods to List Items
The SortedList() Class
Methods for the SortedList() Class
More on the SortedList() Class
“Undoing” the Split Method
The Queue Class 1
The Queue Class 2
The Stack Class 1
The Stack Class 2
Display an ArrayList Content
Advanced Methods on an ArrayList
Members of Collections The Add method adds an item to the end of a collection The Count property returns the number of items in a collection The Item method references an item in a collection The method is 0-based The RemoveAt method removes a collection item The method is also 0-based
Categories of Collections We examine a category of collections for which the type of each element is the same (or the elements are references to elements of the same (parent) type, or of a type derived from the parent type For example, we might have a generic list of elements of type control (parent type) But elements of any control (button, label, etc) as subtypes of the parent can also be stored in the list This type of collection is called a generic list In the slides that follow, we examine generic lists in detail We are interested in how information is structured in these lists when the elements are objects (or object references) The illustrations all use VB examples, but you can translate the examples into C# quite easily.
Creating a Generic List (VB and C#) The Generic List class is used to create collections that store items with the same data type Example to declare a list of type Employee: VB: private EmployeeList As New List(Of Employee) C#: private List<Employee> EmployeeList = new List<Employee>; Here, Employee is Class that is already defined EmployeeList is an object of the special type essentially known as a list of objects of type employee
Creating a List (VB Example) As shown in the diagram below, when a list is first created, space for four items is allocated even though there are no items actually stored in the list Private EmployeeList As New List(Of Employee)
Adding Items to a List An instance of the List class is empty when first created (False) There are no objects of the given base type in the list but the list (of references) itself is created Calling the Add method adds an item to the end of the list The Add method accepts one argument – a reference to the item to add The item added must have the same data type as the data type expected by the list
Adding Items to a List (VB Example) Add two items to a list (What does all this tell us about the data stores (properties) in the Employee class? Private? Public?) Dim EmpCurrent As New Employee ‘Does what? EmpCurrent.EmployeeID = 18223 EmpCurrent.EmployeeName = "Joe Smith" EmployeeList.Add(EmpCurrent) EmpCurrent = New Employee EmpCurrent.EmployeeID = 24428 EmpCurrent.EmployeeName = "Mary Deems"
Memory Allocation Using the List Class (VB Example)
Common List Errors It's possible to add references to the same object to a list This situation is commonly an error but may be the desired outcome How would you do this? Create a new Employee Store the reference to it in both Employee.Item(0) and Employee.Item(1) Note: The list is not properly depicted in the next figure. What is wrong?
Incorrect List References (VB Example)
Referencing a List Item (VB Example) The Item method is used to reference a list item Reference the first Employee in the list named EmployeeList Dim EmpCurrent As Employee EmpCurrent = EmployeeList.Item(0) Debug.WriteLine(EmpCurrent.EmployeeID.ToString) Debug.WriteLine(EmpCurrent.EmployeeName) Create a new Employee and store the reference to it in items (0) and (1) Dim EmpCurrent As New Employee ‘Store useful data (such as the Mary Deems data) in EmpCurrent EmployeeList.Item(0) = EmpCurrent EmployeeList.Item(1) = EmpCurrent Note use of dot operator to select a property EmployeeID of a class (EmpCurrent) Note also conversion and use of DeBug
Updating a Collection Item (VB Example) A collection item can be updated in two ways Replace data stored in an existing item: Note that the Joe Smith data is wiped out because EmpCurrent and EmployeeList.Item(0) point to same list item Replace an item entirely: Replace one class instance with another. Note that the box is the upper right corner of Fig. 8.10 is all wrong. It should read: Dim EmpCurrent as NewEmployee EmpCurrent.EmployeeID = 9999 EmpCurrent.EmployeeName = “Amy Stein” EmployeeList.Item(0) = EmpCurrent
Updating List Items (VB Example)
Replacing List Items (VB Example)
Deleting a Collection Item Call the RemoveAt method with one argument – the 0-based index of the item to remove An exception will be thrown if the index value is invalid Example to remove the first collection item: try EmployeeList.RemoveAt(0); catch ArgumentOutOfRangeException ex MessageBox.Show("Employee not found.");
Size and Capacity of a Collection The Count property stores the number of items in a collection The Capacity property stores the number of items the collection can store Capacity > Count at all times To improve performance, list items are not created one at a time as you need them. The initial value for the Capacity property is 4 The value doubles, as necessary, as Count reaches Capacity
Understanding Lists of Different Types We begin by looking at some code This code illustrates the formation of lists of objects (the parent data type of all other types in VB) as well as lists of integers, and user-defined classes Integers and user-defined classes are all classes derived from the object class We can therefore store objects of any of these types in a list of objects Again – the examples are in VB
Lists of Different Types of Data 1 (vb)
Lists of Different Types of Data 2 There are some important things to note in this code 1. aStruct and aClass are defined elsewhere 2. The methods discussed earlier on generic lists of a single type still work the same here 3. Each list node (struct or class) as created using new is created in the heap and a reference is returned and stored is the “next” available element in the list (Draw a picture based on the previous code) The question is: what happens when primitive types are inserted into a list?
Inserting Primitive Types into a List In C#, primitive types such as integers, and doubles, for example, are considered as objects of types derived from the base type object However, they are not treated that way in the C# implementation – they are treated as value variables, not reference variables “pointing to” objects So how then can we insert them into a list?
Lists of Different Types of Data 3 (optional) Answer – these primitive types are boxed Put another way – these primitive types are automatically promoted (or boxed) to the object data type by the run time system That is, a wrapper object is created in the heap and the primitive variable value is copied into the wrapper object The reference to the wrapper object is then stored in the list. This is depicted below heap Reference to Wrapper object (stored in list) value Wrapper Object
Enumerating a Collection with a For loop A for loop can be used to enumerate the items in a collection A while loop can be similarly used although the for loop is usually preferred A foreach loop can also be used to enumerate the items in a collection We have already examined numerous examples using these looping mechanisms Many more examples can be found in Chapters 5-8 in the text
The TypeOf Statement (Syntax) The TypeOf statement tests the data type of an object result = TypeOf objectExpression Is typeName result contains the Boolean result of testing the object's type result is True if objectExpression is of typeName objectExpression contains an instance of a reference type typeName contains the data type