Chapter 21 Implementing lists: array implementation.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Etter/Ingber Arrays and Matrices. Etter/Ingber One-Dimensional Arrays 4 An array is an indexed data structure 4 All variables stored in an array are of.
Chapter 8: Arrays.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Programming and Data Structure
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
Arrays. Memory organization Table at right shows 16 bytes, each consisting of 8 bits Each byte has an address, shown in the column to the left
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Alice in Action with Java
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
BPJ444: Business Programming Using Java Classes and Objects Tim McKenna
Stacks - 2 Nour El-Kadri ITI Implementing 2 stacks in one array and we don’t mean two stacks growing in the same direction: but two stacks growing.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays Part 4.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
Pemrograman Dasar Arrays PTIIK - UB. Arrays  An array is a container object that holds a fixed number of values of a single type.  The length of an.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Array Cs212: DataStructures Lab 2. Array Group of contiguous memory locations Each memory location has same name Each memory location has same type a.
Lec 6 Data types. Variable: Its data object that is defined and named by the programmer explicitly in a program. Data Types: It’s a class of Dos together.
Arrays Array – Group of contiguous memory locations Each memory location has same name Each memory location has same type.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
CS 161 Introduction to Programming and Problem Solving Chapter 19 Single-Dimensional Arrays Herbert G. Mayer, PSU Status 10/8/2014 Initial content copied.
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 13 – Implementing lists:
C Programming – Part 3 Arrays and Strings.  Collection of variables of the same type  Individual array elements are identified by an integer index 
CS 139-Programming Fundamentals Lecture 11B - Arrays Adapted from a presentation by Dr. Rahman Fall 2014.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Classes, Interfaces and Packages
Arrays An array is an indexed data structure which is used to store data elements of the same data type. An array is an indexed data structure which is.
Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
Review of Java1 Quick Review of ICS 102 Primitive and Reference Types Initializing Class Variables Defining Constructors How to Create a String How to.
Array contiguous memory locations that have the same name and type. Note: an array may contain primitive data BUT an array is a data structure a collection.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
© 2004 Pearson Addison-Wesley. All rights reserved7-1 Array review Array of primitives int [] count; count = new int[10]; Array of objects Grade [] cs239;
 2005 Pearson Education, Inc. All rights reserved Arrays.
Arrays – two dimensional Chapter 14 This chapter explains how to do the following with a two dimensional array: Declare, use indices, obtain size, pass.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Basic Data Types อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา Chapter 4.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Pointers as arrays C++ Programming Technologies. Pointers vs. Arrays Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Object-Oriented Concepts
Arrays (review) CSE 2011 Winter May 2018.
Primitive Types Vs. Reference Types, Strings, Enumerations
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.
Introduction to Data Structure
Arrays in Java.
Java Basics Data Types in Java.
Chap 2. Identifiers, Keywords, and Types
Presentation transcript:

Chapter 21 Implementing lists: array implementation

This chapter discusses n Implementing the class List. n Implementations on a primitive language-provided structure called an array. n Several important relationships between classes used to effect various implementations.

Arrays n array: a structure composed of a contiguous sequence of variables, all of the same type. n Individual variables are identified by index values or indexes. n Index values are integers, (beginning with 0 in Java). n Components or elements are the variables that comprise the array. They are a primitive type ( char, int, boolean, double, etc.) or a reference type (reference to an object).

Arrays (cont.) n The length of the array is the number of component variables that comprise it. n With length n, the component variables are indexed 0 through n-1.

Arrays (cont.) n The length of an array is fixed when the array is created. n Since contiguous memory is allocated for the variables, accessing a particular variable in the array requires a constant amount of time independent of the array length.

Arrays (cont.) n Suppose each variable in a particular array may take up four bytes, and memory is allocated starting at location 100 n The address of the variable with index i is 100+4*i. (starting address)+(variable size)*(element index) n The calculation of the address requires constant time, independent of the index and independent of the size of the array.

Array objects n Arrays in Java are encapsulated in objects. Array objects have a public int component length. n The class of an array is determined by the type of its component variables. n The class is written as the component type followed by a pair of brackets. int[] Student[]

Defining arrays int[] grades; Student[] cs2125; int grades[]; Student cs2125[]; n The variable contains a reference to an array object. n We use a constructor to create the array object. grades = new int[5]; cs2125 = new Student[5];

Defining arrays (cont.)

The component variables of the arrays are initialized with standard default values. e.g. 0 for int, null for references. n The length given in the constructor need not (and generally should not) be a literal. cs2125 = new Student[studentCount]; grades = new int[4*cs2125.length];

Accessing array components A reference to the array is followed by an index value in brackets. grades[3] = 100; grades[4] = grades[3]/2; cs2125[0] = new Student(…); cs2125[0].payFees(100); int i; for(i = 0; i < grades.length; i=i+1) grades[i] = 100; The index value must be an int, non- negative, and less than the length of the array.

Accessing array components (cont.) If an array is referenced with an index that is negative or is not less than the array length, an ArrayIndexOutOfBoundsException is thrown.

BoundedList public abstract class BoundedList A list of objects with a fixed maximum size. protected BoundedList (int maxSize) Create a new BoundedList with a specified maximum size. require: maxSize >= 0 ensure: isEmpty(new BoundedList(n)) Since the class is abstract and an abstract constructor can be invoked only by a subclass, it is declared protected.

BoundedList (cont.) n Component variables: private Object[] elements; private int size; elements will hold the components of the array. size will hold the current length of the list (not the maximum number of elements).

BoundedList (cont.) protected BoundedList (int maxSize){ Require.condition(maxSize >= 0); elements = new Object[maxSize]; size = 0; } public int size() { return this.size; } public Object get (int i) { Require.condition(0 <= i && i < size); return element[i]; } public void append (Object obj) { Require.notNull(obj); Require.condition(size < elements.length); elements[size] = obj; size = size+1; }

BoundedList (cont.) public void add (int i, Object obj) { Require.notNull(obj); Require.condition( 0 <= i && i <= size); Require.condition(size < elements.length); int j; for (j = size-1; j >= i; j = j-1) elements[j+1] = element[j]; elements[i] = obj; size = size + 1; } public void remove (int i) { Require.condition(0 <= i && i < size); int j; for ( j = i; j < size-1; j = j+1) elements[j] = element[j+1]; size = size - 1; }

BoundedList (cont.) public void set (int i, Object obj) { Require.notNull(obj); Require.condition( 0 <= i && i < size); elements[i] = obj; } public void clear () { size = 0; }

BoundedList (cont.) The methods add (and remove ) shuffle a portion of the array up or down. n Elements must be moved starting with the last, or else elements will be overwritten.

BoundedList (cont.) n For instance, if we write for ( j = i; j < size; j= j+1) elements[j+1] = elements[j];

BoundedList (cont.) When elements are deleted with clear or remove, there is no need to set array components to null. n These elements are considered invalid; it does not matter what they contain.

BoundedList (cont.) public boolean isEmpty () { return this.size() == 0; } public int indexOf (Object obj) { int i; int n = this.size(); i = 0; while (i <n && !obj.equals(get(i))) i = i+1; if (i == n) return -1; else return i; }

BoundedList (cont.) public String toString () { String s = [; int n = this.size(); if (n > 0) { s = s + this.get(0).toString(); int i; for(i = 1; i < n; i = i+1) s = s +, + this.get(i).toString(); } s= s + ]; } public int maxSize () { return elements.length; }

The method copy n We make a shallow copy of the list. i.e. the original list and the copy reference the same list elements.

The method copy (cont.) public BoundedList copy() { int i; BoundedList theCopy = new BoundedList(elements.length); for (i = 0; i < size; i=i+1) { theCopy.elements[i] = this.elements[i]; theCopy.size = this.size; return theCopy; } //This doesnt work because BoundedList is an abstract class.

Java Interface Cloneable Object class has a method clone. protected Object clone () throws CloneNotSupportedException Create a copy of this Object. n This method has these properties s != s.clone() s.equals(s.clone()); s.clone() instanceof Student //of course we are implying that s is a Student. Since clone returns an object, it is often necessary to cast the result. Student s2 = (Student) s.clone();

Java Interface Cloneable (cont.) public interface Cloneable {} Any class that supports the method clone should implement this interface. If not, a CloneNotSupportedException is thrown. The method clone works essentially like this: if (this instanceof Cloneable) { Object copy = new instance of this class; for each component variable v of this copy.v = this.v; return copy; else throw CloneNotSupportedException;

Java Interface Cloneable (cont.) Implementing the interface does not require a class to implement any methods; the class inherits the method clone implemented in the class Object.

Java Interface Cloneable (cont.) If Java were built with multiple inheritance, Cloneable would be a class from which other objects could inherit and the method clone would be defined there.

Java Interface Cloneable (cont.) It simply turns on the method clone inherited from Object.

BoundedList public abstract class BoundedList implements Clonable { … public Object clone() { BoundedList theCopy = (BoundedList)super.clone(); …

BoundedList (cont.) n We may want a less shallow copy of the list so that we can manipulate the list and its clone independently.

BoundedList (cont.) public Object clone() { try { BoundedList theCopy = (BoundedList)super.clone(); theCopy.elements = (Object[])this.elements.clone(); return theCopy; } catch (CloneNotSupportedException e) { return null; }

Implementation n We need to cast the result explicitly to BoundedList or Object[ ] as appropriate. Javas scoping rules allow private components of the BoundedList theCopy to be accessed directly in the method. Since the Object method clone is specified as possibly throwing a CloneNotSupportedException, we must include a try statement and catch it, or include a throws clause in the specifications of the method.

Implementation (cont.) n In order to have an abstract class that creates a new object, we implement a method like this: public BoundedList copy () { return (BoundedList) this.clone(); } The object created by the call to super.clone() will be of the same run- time class as the object executing the call.

Abstract Constructor n An abstract method can be used like a constructor for creating objects in a superclass. n Sometimes it is called a factory method. n Subclasses implement the method and determine which actual concrete class to instantiate. public abstract BoundedList createList (int maxSize) Create a new BoundedList with a specified maximum size. require: maxSize >= 0 ensure: isEmpty(createList(n))

Abstract constructor (cont.)

public class BoundedStudentList extends BoundedList { … /** * Create a new BoundedStudent list * require: * maxSize >= 0 * ensure: * isEmpty(createList(n)) *createList(n) instanceof * BoundedStudentList */ public BoundedList createList (int maxsize) { return new BoundedStudentList (maxsize); } … }

Abstract constructor (cont.) public BoundedList copy() { int i; BoundedList theCopy = createList( this.element.size); for (i = 0; i < this.size; i=i+1) theCopy.elements[i]=this.elements[i]; theCopy.size = this.size; return theCopy; }

Advantages of arrays Elements can be accessed efficiently; get, append, and set all operate in constant time.

Limitations of arrays n The array is static. The client must have a good idea of the ultimate size of a list when the list is created. u Too large means wasted space. u Too small causes failure. Operations remove, add, and indexOf all are linear. n Conclusions u Not the best implementation for dynamic lists. u Often a good choice for static lists.

Dynamic arrays n A bounded list has a maximum size. n A dynamic list has no maximum size. n A static array can be made into a dynamic array by simply creating a bigger array when the original array is full.

Dynamic lists public void append (Object obj) { Require.notNull(obj); if (this.size == elements.length) { // need a bigger array Object[] newArray = new Object[2*elements.length]; //copy contents of old array to new int i; for(i = 0; i < elements.length; i=i+1) newArray[i] = elements[i]; elements = newArray; } elements[size] = obj; size = size +1; }/*append becomes a very expensive operation because there is the possibility of having to copy the entire array into a new array. (linear time) */

Vector class n Vector class is a container class that encapsulates a dynamic use of arrays. public Vector (); public Vector (int initialCapacity); public Vector (int initialCapacity, int capacityIncrement); New Vector (100,20) default initialCapacity = 10 default capacityIncrement = 0 capacityIncrement of 0 means it doubles everytime it outgrows capacity.

Wrapper n A class that adds functionality to or modifies the specification of another class. n A class that provides required functionality but lacks the required interface can be tailored to fit our needs by wrapping the class in a wrapper class. n Vector has all of the functionality and most of the methods of lists.

Wrapper specifications public Object elementAt(int index); The element at the given array index. public int indexOf (Object elem) Index of the given element; -1 if the array does not contain the element. public int size () The number of elements in the Vector. public Object clone() A new copy of the Vector. public void addElement (Object elem) Add the element to the end of the Vector; size is increased, and capacity is incremented if necessary. public void insertElementAt (Object obj, int index) Add the given element at the given array index, shifting elements up as necessary.

Wrapper specifications (cont.) public void removeElementAt (int index) Remove the element at the given index, and shift higher indexed elements down. public void setElementAt (Object obj, int index) Replace the element at the specified array index with the Objectt provided. public String toString() A string representation of this Vector, containing the String representation of each element. public void removeAllElements() Removes all the components from this Vector and sets its size to zero. n The time complexity of the methods is the same as with BoundedList.

Weve covered n Javas array classes n Object arrays used to implement a version of the class List n Cloning arrays n Solving the fixed array limitation u Vectors u Dynamic arrays u Wrappers n Time complexities.

Glossary