240 likes | 681 Views
Object Oriented Programming. Collections. Briana B. Morrison CSE 1302C Spring 2010. Topics. What is OOP? Why OOP? Collections. Object-Oriented Design Goals. Software should be: robust adaptable reusable How does OOD address these?. Object-Oriented Design Principles. Abstraction
E N D
Object Oriented Programming Collections Briana B. Morrison CSE 1302C Spring 2010
Topics What is OOP? Why OOP? Collections
Object-Oriented Design Goals • Software should be: • robust • adaptable • reusable • How does OOD address these?
Object-Oriented Design Principles • Abstraction • Encapsulation • Modularity
Collections • Arrays are good for fast/immediate access to the data, but their limitation is that they are fixed in size. To overcome this, collections that are dynamic allow us to grow/shrink the data structure. • High-level APIs provide a means to access these dynamic collections similar to arrays (and use the [ ] index notation), but realize that there is a lot of memory management that is happening behind the scenes.
ArrayList • Many languages provide a means to manage polymorphic collections such as the ArrayList (in C#). • This is polymorphic in that it holds elements of type "object", and all classes implicitly inherit from "object". This is what provides the "Equals()", "ToString()", etc. methods that all things have. • Sample syntax: ArrayList collection = new ArrayList(); collection.Add(42); collection.Add("Dog"); collection.Add(new Vector2(5,7)); • This is permissible because the int, string, and Vector2 class are all instances of the "object" class (via inheritance).
ArrayList • The problem with the ArrayList (and any polymorphic collection) is that you must be careful in handling the data when you access it. • You could not, for example do something like this (since all elements may not be ints): foreach (inti in collection) { // do something } • This may generate an invalid typecast exception.
Parameterized Collections • To overcome the limitations of polymorphic collections (and for performance/memory issues that we won't get into right now), modern languages also provide a means by which you can explicitly state the type of thing you want the collection to manage. You do this via a "parameter" to the class when you define it. • For example, we can use the List<T> class in C# to accomplish this (where T is the type we want the list to hold). List<int> numbers = new List<int>(); numbers.Add(42); numbers.Add(9);
List class • Some useful methods/attributes of the List<T> class are: • Count • Capacity • Add() • RemoveAt(int) • Insert(int,T)
List class • Since the type that the collection holds is known, we can do something like this: foreach (inti in numbers) { Console.WriteLine(i); } • And you can also access the elements via the [ ] index notation as in: numbers[0] = 8;