Lecture Set 9 Arrays, Collections, and Repetition

Slides:



Advertisements
Similar presentations
Lists, Loops, Validation, and More
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Stacks, Queues, and Deques
Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
1 Week 6 The Repetition Structure. 2 The Repetition Structure (Looping) Lesson A Objectives After completing this lesson, you will be able to:  Code.
Tutorial 6 The Repetition Structure
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Class Average Application Introducing the Do...Loop While and Do...Loop Until.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
Understanding Data Types and Collections Lesson 2.
 A ListBox control displays a list of items and allows the user to select one or more  Drag from Toolbox to create this control on a form.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
Chapter 8: Understanding Collections Textbook: Chapter 4.
Arrays Chapter 7.
Understanding Data Types and Collections Lesson 2.
JavaScript, Sixth Edition
Review Array Array Elements Accessing array elements
User-Written Functions
Pointers and Linked Lists
Pointers and Linked Lists
Linked Lists in Action Chapter 5 introduces the often-used data public classure of linked lists. This presentation shows how to implement the most common.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Chapter 20 Generic Classes and Methods
Computer Programming I
Linked lists.
Single Dimensional Arrays
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Using Procedures and Exception Handling
IS 350 Loops.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Top Ten Words that Almost Rhyme with “Peas”
Files and Streams Lect3 CT1411.
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Arrays, Collections and Repetition Part A – Arrays and Repetition
CS313D: Advanced Programming Language
VISUAL BASIC.
OOP Paradigms There are four main aspects of Object-Orientated Programming Inheritance Polymorphism Abstraction Encapsulation We’ve seen Encapsulation.
Stacks, Queues, and Deques
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Java Programming Arrays
Benchmark Series Microsoft Word 2016 Level 2
Programming II (CS300) Chapter 07: Linked Lists and Iterators
Dynamic Data Structures and Generics
Object Oriented Programming in java
Classes and Objects.
Lecture Set 10 Windows Controls and Forms
3.1 Iteration Loops For … To … Next 18/01/2019.
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
Object-Oriented Programming: Inheritance and Polymorphism
Object-Oriented Programming Using C++ Second Edition
Dynamic Data Structures and Generics
Introduction to Data Structure
Java Programming Language
Submitted By : Veenu Saini Lecturer (IT)
Data Structures & Algorithms
Review: libraries and packages
Stacks, Queues, and Deques
Linked lists.
Introduction to Computer Programming IT-104
Arrays.
Creating and Using Classes
Presentation transcript:

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