Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring 2014 1 COS 240 Object-Oriented Languages.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

Generics, Lists, Interfaces
Introduction to Arrays Chapter What is an array? An array is an ordered collection that stores many elements of the same type within one variable.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Generics and the ArrayList Class
Object-Oriented PHP (1)
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Collections. 2 Objectives Explore collections in System.Collections namespace –memory management –containment testing –sorting –traversal.
Inheritance, Shared. Projectiles Program Demonstrates – Inheritance – MustInherit – Shared vs. Non-shared methods A variation on the Multiball example.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
ArrayLists.  The Java API includes a class named ArrayList. The introduction to the ArrayList class in the Java API documentation is shown below.  java.lang.Object.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
Lecture 5 What is object-oriented programming OOP techniques How Windows Forms applications rely on OOP.
Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Object Composition Interfaces Collections Covariance Object class Programming using C# LECTURE 10.
4.1 Instance Variables, Constructors, and Methods.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Unit 3: Java Data Types Math class and String class.
Chapter 10 Strings, Searches, Sorts, and Modifications Midterm Review By Ben Razon AP Computer Science Period 3.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
Spring 2005, Gülcihan Özdemir Dağ Lecture 7, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 7 Outline 7. 1.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Introduction to LINQ Chapter 11. Introduction Large amounts of data are often stored in a database—an organized collection of data. A database management.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
Linked List. Iterators Operation to find a link, deleting, and inserting before or after a specified link, also involve searching through the list to.
Understanding Data Types and Collections Lesson 2.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
Operator Overloading Week 5.
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
Final Review. From ArrayLists to Arrays The ArrayList : used to organize a list of objects –It is a class in the Java API –the ArrayList class uses an.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
Introduction to Object-Oriented Programming Lesson 2.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
CSI 3125, Preliminaries, page 1 Data Type, Variables.
Word Create a basic TOC. Course contents Overview: table of contents basics Lesson 1: About tables of contents Lesson 2: Format your table of contents.
Lecture 10: Generics & Basic Desktop Programming Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
Object Oriented Software Development 6. Arrays and collections.
CSE 1201 Object Oriented Programming ArrayList 1.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 9: Arrays; Revision Session.
PaintPictureBoxDemo Refers to the PaintPictureBoxDemo Visual Basic Program Included With The Lecture.
Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Chapter 11.  Large amounts of data are often stored in a database—an organized collection of data.  A database management system (DBMS) provides mechanisms.
Functional Processing of Collections (Advanced) 6.0.
Understanding Data Types and Collections Lesson 2.
Lecture 10 Collections Richard Gesick.
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.
Functional Processing of Collections (Advanced)
CS313D: Advanced Programming Language
Lecture 10: Collections.
Type & Typeclass Syntax in function
Java Programming Language
Fundaments of Game Design
Lecture Set 9 Arrays, Collections, and Repetition
Presentation transcript:

Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages

WHAT YOU WILL LEARN How to define and use collections The different types of collections that are available How to compare types and use the is operator How to compare values and overload operators How to define and use conversions How to use the as operator 2

Course Materials – Source Codes 3

Collections Collections enable you to maintain groups of objects. Unlike arrays, which you’ve used in earlier chapters, collections can include more advanced functionality, such as controlling access to the objects they contain, searching and sorting, and more. You’ll learn how to use and create collection classes and learn about some powerful techniques for getting the most out of them. 4

Comparisons When dealing with objects, you often want to make comparisons between them. This is especially important in collections, because it is how sorting is achieved. You’ll look at how to compare objects in a number of ways, including operator overloading, and how to use the IComparable and IComparer interface to sort collections. 5

Conversions Earlier lectures showed you how to cast objects from one type into another. In this lecture, you’ll learn how to customize type conversions to suit your needs. 6

Collections The biggest limitation is that once arrays have been created, they have a fixed size, so you can’t add new items to the end of an existing array without creating a new one. This often means that the syntax used to manipulate arrays can become overly complicated. OOP techniques enable you to create classes that perform much of this manipulation internally, simplifying the code that uses lists of items or arrays. Arrays in C# are implemented as instances of the System.Array class and are just one type of what are known as collection classes. Collection classes in general are used for maintaining lists of objects, and they may expose more functionality than simple arrays. Much of this functionality comes through implementing interfaces from the System.Collections namespace, thus standardizing collection syntax. This namespace also contains some other interesting things, such as classes that implement these interfaces in ways other than System.Array. 7

Collections Because the collection’s functionality (including basic functions such as accessing collection items by using [index] syntax) is available through interfaces, you aren’t limited to using basic collection classes such as System.Array. Instead, you can create your own customized collection classes. These can be made more specific to the objects you want to enumerate (that is, the objects you want to maintain collections of). One advantage of doing this, as you will see, is that custom collection classes can be strongly typed. That is, when you extract items from the collection, you don’t need to cast them into the correct type. Another advantage is the capability to expose specialized methods. For example, you can provide a quick way to obtain subsets of items. In the deck of cards example, you could add a method to obtain all Card items of a particular suit. 8

Collections 9

Using Collections One of the classes in the Systems.Collections namespace, System.Collections.ArrayList, also implements IList, ICollection, and IEnumerable, but does so in a more sophisticated way than System.Array. Whereas arrays are fixed in size (you can’t add or remove elements), this class can be used to represent a variable-length list of items. To give you more of a feel for what is possible with such a highly advanced collection, the following Try It Out uses this class, as well as a simple array. 10

Defining Collections One way to create your own strongly typed collection is to implement the required methods manually, but this can be a time-consuming and complex process. Alternatively, you can derive your collection from a class, such as System.Collections.CollectionBase, an abstract class that supplies much of the implementation of a collection for you. This option is strongly recommended. 11

12

13

Indexers An indexer is a special kind of property that you can add to a class to provide array-like access. In fact, you can provide more complex access via an indexer, because you can define and use complex parameter types with the square bracket syntax as you want. Implementing a simple numeric index for items, however, is the most common usage. 14

You can add an indexer to the Animals collection of Animal objects as follows: 15

Indexers The this keyword is used along with parameters in square brackets, but otherwise the indexer looks much like any other property. This syntax is logical, because you access the indexer by using the name of the object followed by the index parameter(s) in square brackets (for example, MyAnimals[0]). The indexer code uses an indexer on the List property (that is, on the IList interface that provides access to the ArrayList in CollectionBase that stores your items): return (Animal)List[animalIndex]; Explicit casting is necessary here, as the IList.List property returns a System.Object object. The important point to note here is that you defi ne a type for this indexer. This is the type that will be obtained when you access an item by using this indexer. This strong typing means that you can write code such as animalCollection[0].Feed(); rather than: ((Animal)animalCollection[0]).Feed(); This is another handy feature of strongly typed custom collections. In the following Try It Out, you expand the previous Try It Out to put this into action. 16

Keyed Collections and IDictionary 17

18

19

20

Iterators Earlier you saw that the IEnumerable interface enables you to use foreach loops. It’s often beneficial to use your classes in foreach loops, not just collection classes such as those shown in previous sections. However, overriding this behavior, or providing your own custom implementation of it, is not always simple. To illustrate this, it’s necessary to take a detailed look at foreach loops. The following steps show you what actually happens in a foreach loop iterating through a collection called collectionObject: 1) collectionObject.GetEnumerator() is called, which returns an IEnumerator reference. This method is available through implementation of the IEnumerable interface, although this is optional. 2) The MoveNext() method of the returned IEnumerator interface is called. 3) If MoveNext() returns true, then the Current property of the IEnumerator interface is used to get a reference to an object, which is used in the foreach loop. 4) The preceding two steps repeat until MoveNext() returns false, at which point the loop terminates. 21

22

23

24

Iterators and Collections 25

26

Comparisons There are two types of comparisons between objects: Type comparisons - determining what an object is, or what it inherits from — are important in all areas of C# programming. Often when you pass an object — to a method, for example — what happens next depends on the type of the object. Value comparisons - Value comparisons are also something you’ve seen a lot of, at least with simple types. When it comes to comparing values of objects, things get a little more complicated. You have to define what is meant by a comparison for a start, and what operators such as > mean in the context of your classes. This is especially important in collections, for which you might want to sort objects according to some condition, perhaps alphabetically or according to a more complicated algorithm. 27

Type Comparisons 28

Boxing and Unboxing 29

30

Boxing 31

Unboxing 32

The is Operator 33

Value Comparisons 34

Operator Overloading 35

36

37

38

39

40

41

42

43

The IComparable and IComparer Interfaces 44

45

46

47

48

Sorting Collections 49

CONVERSIONS Thus far, you have used casting whenever you have needed to convert one type into another, but this isn’t the only way to do things. Just as an int can be converted into a long or a double implicitly as part of a calculation, you can define how classes you have created can be converted into other classes (either implicitly or explicitly). To do this, you overload conversion operators, much like other operators were overloaded earlier in this lecture. You’ll see how in the first part of this section. You’ll also see another useful operator, the as operator, which in general is preferable to casting when using reference types. 50

Overloading Conversion Operators As well as overloading mathematical operators, as shown earlier, you can define both implicit and explicit conversions between types. This is necessary if you want to convert between types that aren’t related — if there is no inheritance relationship between them and no shared interfaces 51

Examples 52

53

54

The as Operator 55

56

57

More reading: Karli Watson et all, Beginning Visual C# 2012 Programming, Wrox, Jonh Wiley & Sons, 2013 CHAPTER 11: Collections, Comparisons and Conversions. 58

59 Questions?