Arrays and Lists.  Properties ◦ Contents are stored in contiguous memory locations ◦ Elements of the array are of the same type  (Perl allows for.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Generics, Lists, Interfaces
Introduction to Linked Lists In your previous programming course, you saw how data is organized and processed sequentially using an array. You probably.
1 Various Methods of Populating Arrays Randomly generated integers.
Basic Algorithms on Arrays. Learning Objectives Arrays are useful for storing data in a linear structure We learn how to process data stored in an array.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Chapter 10.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Alice in Action with Java
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 7: Working with Arrays
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
A First Book of ANSI C Fourth Edition
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
ArrayList, Multidimensional Arrays
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
Chapter 8: Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Pointers OVERVIEW.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Java Basics.  To checkout, use: svn co scb07f12/UTORid  Before starting coding always use: svn update.
Understanding Data Types and Collections Lesson 2.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
C arrays are limited: -they are represented by pointers (which may or may not be valid); -Indexes not checked (which means you can overrun your array);
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Object Oriented Software Development 4. C# data types, objects and references.
Composition When one class contains an instance variable whose type is another class, this is called composition. Instead of inheritance, which is based.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Session 02 Module 3: Statements and Operators Module 4: Programming constructs Module 5: Arrays.
Pointers in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
Value Types. 2 Objectives Discuss concept of value types –efficiency –memory management –value semantics –boxing –unboxing –simple types Introduce struct.
Objectives You should be able to describe: One-Dimensional Arrays
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Understanding Data Types and Collections Lesson 2.
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.
CS313D: Advanced Programming Language
Object Oriented Programming in java
Data Structures (CS212D) Week # 2: Arrays.
Arrays Week 2.
7 Arrays.
Java Programming Language
Review: libraries and packages
COP 3330 Object-oriented Programming in C++
Presentation transcript:

Arrays and Lists

 Properties ◦ Contents are stored in contiguous memory locations ◦ Elements of the array are of the same type  (Perl allows for different types, but then Perl’s strange that way) ◦ Direct access of elements possible using a cardinal indexer  Index is used as the “offset” from the beginning of the array ◦ Operations  Allocation  Accessing

 C# ◦ Initial declaration makes a “null” value array  bool [] booleanArray;  arrayName = new arrayType[allocationSize]; ◦ Contiguous block of memory is allocated  Which is why the allocation size is required up front  Adding elements later cannot extend this memory “block”  Each element in the array is of the “type”  bool or int would be elements of that type value  FileInfo is a reference, so the elements would be of that type, which are references to the actual objects, and not the object per se bool [] booleanArray; FileInfo [] files; booleanArray = new bool[10]; files = new FileInfo[10];

// Read an array element bool b = booleanArray[7]; // Write to an array element booleanArray[0] = false;  Running time is O(1) ◦ Constant, regardless of how many elements are stored  In reality  Managed code  Lookup will take extra running time for integrity (index- bounds) check of element costing performance  Possible to use unmanaged code for access

 Make a larger array and then copy the old over array to the new array ◦ Unassigned values in the new array have the default “0” value ◦ Don’t forget that the old array is still allocated in memory // Create an integer array with three elements int [] fib = new int[3]; fib[0] = 1; fib[1] = 1; fib[2] = 2; // Redimension message to a 10 element array int [] temp = new int[10]; // Copy the fib array to temp fib.CopyTo(temp, 0); // Assign temp to fib fib = temp;

 Good for ◦ storing homogeneous data types ◦ Only accessing them directly  Searching unsorted array ◦ Linear running time  If storing large arrays which are searched frequently ◦ Consider other structures  Sorted array ◦ Binary search can be used to search the array  Running time is O(log N)  Array class has a BinarySearch() method  Multidimensional arrays ◦ Runtime is O(N k ) where “k” is the number of dimension

 Customization of a structure for application ◦ Process array of class Employee with its methods and properties  might want extra functionality not present in array or in order to resize the array if needed  Create a custom data structure with of Employee  Or.. The array can be of type object  This can store any data type (all types derive from object in.Net Framework) .Net Framework has such a structure  System.Collections.ArrayList class  Internal object array  When reading value from ArrayList, cast it to data type being stored

 Flexibility is obtained at the expense of performance ◦ Each array element is a reference to an object

 Performance cost due to indirection and boxing/unboxing of data ◦ Boxing is the conversion a value type to a reference type  Allocate memory from heap  Amount of memory is size needed by the value type plus additional overhead to make this an object  Pointer to virtual method table and pointer to a ‘sync block’  Copy value type’s bit to heap  Return address of the object (reference type) ◦ Unboxing  Retrieve a reference to the value type in an object  CLR checks reference type variable is not null and boxed value of the type desired  Pointer to the value is returned  Array of objects ◦ Potential run time errors  Wrong data type is added to an element at run time  This is not caught at compile time  Bug won’t be caught until testing or actual production run  Typing problem with ArrayList is fixed in.Net Framework with Generics

public class TypeSafeList { T[] innerArray = new T[0]; int currentSize = 0; int capacity = 0; public void Add(T item) { // see if array needs to be resized if (currentSize == capacity) { // resize array capacity = capacity == 0 ? 4 : capacity * 2; // double capacity T[] copy = new T[capacity]; // create newly sized array Array.Copy(innerArray, copy, currentSize); // copy over the array innerArray = copy; // assign innerArray to the new, larger array } innerArray[currentSize] = item; currentSize++; } Type identifier (T) is defined. Requires developer to specify a SINGLE type (aliased as “T”).

public T this[int index] { get { if (index = currentSize) throw new IndexOutOfRangeException(); return innerArray[index]; } set { if (index = currentSize) throw new IndexOutOfRangeException(); innerArray[index] = value; } public override string ToString() { string output = string.Empty; for (int i = 0; i < currentSize - 1; i++) output += innerArray[i] + ", “; return output + innerArray[currentSize - 1]; }

TypeSafeList variableName;  Sample code TypeSafeList fib = new TypeSafeList (); fib.Add(1); for (int i = 2; i < 25; i++) fib.Add(fib[i - 2] + fib[i - 1]); Console.WriteLine(fib.ToString());

 Benefits ◦ Type safety  Can only add elements of “type” declare or derived from declared type  Adding a string to the “fib” example would result in a compile time error rather than run time error ◦ Performance  No type checking required at run time  Boxing/unboxing is eliminated ◦ Reusable  Break the coupling between the data structure and the specific application for which it was created

 Homogeneous array  Self-redimensioning array  List is a “wrapper” for array ◦ Provides read/write access to array ◦ Automatically resizes the array as required ◦ Utilizes Generics  Type is specified at development time  Specified in declaration and instantiation of List  No size is required in declaration  Can specify a default starting size in the constructor  Can use the List.Capacity property to specify  Add() method is used to add an item  Items accessible via an ordinal index

// Create a List of integers List myFavoriteIntegers = new List (); // Create a list of strings List friendsNames = new List ();  Sample // Create a List of integers List powersOf2 = new List (); // Add 6 integers to the List powersOf2.Add(1); powersOf2.Add(2); powersOf2.Add(4); powersOf2.Add(8); powersOf2.Add(16); powersOf2.Add(32); // Change the 2nd List item to 10 powersOf2[1] = 10; // Compute 2^3 + 2^4 int sum = powersOf2[2] + powersOf2[3];

 To find an element in an array, you must process each element in a loop ◦ unless the array is sorted  List has ◦ Contains() method ◦ IndexOf() method ◦ BinarySearch() method ◦ Find() ◦ FindAll() ◦ Sort() ◦ ConvertAll()  Running time of the List’s operations is the same as the standard array’s running time