An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 13 – Implementing lists:

Slides:



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

Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Chapter 21 Implementing lists: array implementation.
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 14: Sorting and Searching.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Mutable, Immutable, and Cloneable Objects Chapter 15.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
List Implementations That Use Arrays Chapter 5. 2 Chapter Contents Using a Fixed-Size Array to Implement the ADT List An Analogy The Java Implementation.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Alice in Action with Java
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
CS2110 Recitation Week 8. Hashing Hashing: An implementation of a set. It provides O(1) expected time for set operations Set operations Make the set empty.
Arrays And ArrayLists - S. Kelly-Bootle
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Pointer Data Type and Pointer Variables
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.
04/29/ Introduction to Vectors?... A vector is a dynamic array. - It can be expanded and shrunk as required - A Component of a vector can be accessed.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CSC 212 Stacks & Queues. Announcement Many programs not compiled before submission  Several could not be compiled  Several others not tested with javadoc.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Pointer and Array Lists Chapter 3, Summary CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 6 : Testing.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 8: Putting a System Together.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Generics. Writing typed checked generic code There are many instances where the type of the object is irrelevant : –The construction of data structures.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
C19: Collection Classes (don’t forget to look at all the online code examples)
Implementing ArrayList Part T2 Lecture 6 School of Engineering and Computer Science, Victoria University of Wellington  Thomas Kuehne, Marcus Frean,
Chapter 9 Introduction to Arrays Fundamentals of Java.
Building Java Programs Generics, hashing reading: 18.1.
An Array-Based Implementation of the ADT List
Implementing ArrayList Part 1
Programming in Java Lecture 11: ArrayList
Chapter 12 : Lists.
Programming II (CS300) Chapter 07: Linked Lists and Iterators
ArrayLists 22-Feb-19.
Introduction to Data Structure
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
Chapter 8 Class Inheritance and Interfaces
Presentation transcript:

An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 13 – Implementing lists: array implementations

1May 2004NH-Chapter 13 Objectives ñAfter studying this chapter you should understand the following: ñthe idea of an array and array index; ñlist implementations using arrays and the Vector class; ñshallow and deep copies;  the method clone and the interface Cloneable.

2May 2004NH-Chapter 13 Objectives ñAlso, you should be able to: ñdefine array variables, create arrays, and access array components; ñwrite algorithms having arrays as parameters; ñdefine classes whose components include array instances.

3May 2004NH-Chapter 13 Anatomy of an array IndicesVariables ña contiguous sequence of variables. ñall of the same type. ñEach variable is identified by its index. ñIndex values are integers. ñIndex of first entry is 0.

4May 2004NH-Chapter 13 Arrays ñType of array element  primitive type ( char, int, boolean, double, etc.) ñor  reference type (Student, PlayingCard, Object, etc.) ñLength of array: number of component variables  If length of array is n, index range from 0 to n - 1. ñlength of array is fixed after creation. ñAccess of an array variable is in constant time

5May 2004NH-Chapter 13 Arrays ñThey are subclass of Object.  Have a public final int component length.  int[] denotes the class array-of- int,  Student[] denotes the class array-of-Student.

6May 2004NH-Chapter 13 Defining arrays ñNote: declaring the variable does not create an array. grades cs2125 int[] grades;  Creates an array-of- int named grades Student[] cs2125;  Creates an array-of-Student named cs2125.

7May 2004NH-Chapter 13 Defining arrays ñcreate two arrays of length 5, and ñassign references to specified variables grades int[ ] 0 length cs2125 Student[ ] 0 length grades = new int[5]; cs2125 = new Student[5];

8May 2004NH-Chapter 13 Accessing array components grades[3]  is an int variable –We can also write: grades[3] = 100; grades[4] = grades[3]/2;

9May 2004NH-Chapter 13 Accessing array components ñSimilarly, we can write: ñImportant: index value used to access an array variable must be in range 0 to length of array - 1 cs2125[0] = new Student(…); cs2125[0].payFees(100);

10May 2004NH-Chapter 13 Initializing array variables  Can assign each component of array grades 100 via: for (int i = 0; i < grades.length; i = i+1) grades[i] = 100;

11May 2004NH-Chapter 13 ArrayIndexOutOfBoundsException  Stores value 100 in all components of array grades, but fails on last iteration when i equals grades.length with error ArrayIndexOutOfBoundsException for (int i = 0; i <= grades.length; i = i+1) grades[i] = 100; ñA negative index or greater than or equal to array length – results in a run-time error ArrayIndexOutOfBoundsException.

12May 2004NH-Chapter 13 Implementing List using an array ñAllocate array to hold references to elements of list. ñarray is a list component containing the list elements. ñArray component 0 references first element of list, component 1 references the second, and so on. ñLength of list is bounded by length of array, and array length is fixed when the array is created.

13May 2004NH-Chapter 13 Implementing List using an array ñCall list implementation class using an array BoundedList ñ Require that a maximum list size be specified when an instance is created.

14May 2004NH-Chapter 13 BoundedList and List ñProblem: List interface does not put a requirement on the size of lists. ñBoundedList must place a requirement in its add methods: ñlist size be less than its maximum for add to occur.  Preconditions for BoundedList add are stronger than the preconditions for List add. ñBoundedList should not be a subtype of List. ñImplement BoundedList as an independent class.

15May 2004NH-Chapter 13 BoundedList constructor  Ensure guarantees to create an empty list.  The implementation array size is maxSize.  Naming BoundedList’s array component elements: elements.length == maxSize public class BoundedList A list of Elements with a fixed maximum size. public BoundedList (int maxSize) Create a new BoundedList with a specified maximum size. require: maxSize >= 0 ensure: i sEmpty(new BoundedList(n))

16May 2004NH-Chapter 13 BoundedList data components  Data components ñ array containing the elements,  an int variable containing list length.

17May 2004NH-Chapter 13 BoundedList data components ñWe cannot define: Not legal code!! private Element[] elements; ñNot legal to define an array using the type parameter, Element, to specify type of array entries. ñFor arrays must use Object as type of its entries. private Object[] elements; // elements of the list private int size; // size of the list

18May 2004NH-Chapter 13 Constructor implementation  Example of use: public BoundedList (int maxSize) { assert maxSize >= 0; elements = new Object[maxSize]; size = 0; } BoundedList roll = new BoundedList (5);

19May 2004NH-Chapter 13 add(int I, Element elm) implementation  add(int,Element) shuffles portion of the array down. ñExample: list contains six elements, and a new element is to be inserted at index position 2. ñEntries at indices : 2,3,4,5 must be moved down, starting with the last, to make room for new element.

20May 2004NH-Chapter 13 remove(int index) implementation  remove(int) shuffles portion of the array up. ñExample: list contains six elements, and must remove element at index position 2 ñentries at indices : 2,3,4,5 must be moved up, starting with the the one at index 3.

21May 2004NH-Chapter 13 BoundedList implementation public Element get (int index) { assert 0 <= index && index < size; return (Element)elements[index]; } public int indexOf (Element element) { int i = 0; while (i < size && !element.equals(elements[i]) i = i+1; if (i < size) return i; else return -1; }

22May 2004NH-Chapter 13 BoundedList implementation public void add (Element element) { assert size < elements.length; elements[size] = element; size = size+1; } public void add (int index, Element element) { assert 0 <= index && index <= size; assert size < elements.length; for (int i = size-1; i >= index; i = i-1) elements[i+1] = elements[i]; elements[index] = element; size = size+1; }

23May 2004NH-Chapter 13 BoundedList implementation public void set (int index, Element element) { assert 0 <= index && index < size; elements[index] = element; } public void remove (int index) { assert 0 <= index && index < size; for (int i = index; i < size-1; i = i+1) elements[i] = elements[i+1]; size = size-1; }

24May 2004NH-Chapter 13 Copies and Clones  For objects with lists as components values, provide a query that returns a copy of the list component rather than list itself.

25May 2004NH-Chapter 13 Copies and Clones ñshallow copy : list is copied, but not its elements. public BoundedList copy () { BoundedList theCopy = new BoundedList (this.elements.length); theCopy.size = this.size; for (int i = 0; i < this.size; i = i+1) theCopy.elements[i] = this.elements[i]; return theCopy; }

26May 2004NH-Chapter 13 A shallow copy of a list: ref entries are copied. BoundedList this elements size 3 Object[ ] 0 length Student ?? BoundedList theCopy elements size 3 Object[ ] 0 length

27May 2004NH-Chapter 13 A deep copy of a list: components are copied. elements size 3 Object[ ] 0 length Student c ?? BoundedList theCopy elements size 3 Object[ ] 0 length Student b a cCopy Student bCopy Student aCopy

28May 2004NH-Chapter 13 clone method  The class Object defines a method clone specified as protected Object clone () throws CloneNotSupportedException Create a copy of this Object.  “ throws CloneNotSupportedException ” means method may fail during execution

29May 2004NH-Chapter 13 clone method  Object’s clone produces a very shallow copy of the Object: all instance variable values are copied.

30May 2004NH-Chapter 13 Relationship between an object and its clone ñIf obj is an object : obj != obj.clone() obj.equals(obj.clone()) obj instanceof someType if and only if obj.clone() instanceof someType  Since clone returns an Object, you must cast result: Date date1 = new Date(…); Date date2 = (Date)date1.clone();

31May 2004NH-Chapter 13 Cloneable interface ñIt’s an interface with no methods.  Implemented by any class that supports (or overrides) clone.  clone checks to see if object is an instance of a class implementing Cloneable. ñIf so, makes shallow copy of object. ñOtherwise, fails with CloneNotSupportedException. public interface Cloneable { };

32May 2004NH-Chapter 13 BoundedList copy  We choose not to define BoundedList to implement Cloneable  If we do, clone() forces us to define equals() in BoundedList.  BoundedList is a mutable class, with no immutable set of properties to define equals() ñWe provide our own copy algorithm.

33May 2004NH-Chapter 13 Advantages and limitation of array implementations KList elements can be accessed in constant time :  get(int),  add(Element),  set(int,Element). _The following operations are linear:  remove(int),  add(int,Element),  indexOf(Element)

34May 2004NH-Chapter 13 Advantages and limitation of array implementations ðNumber of steps required (for add, remove) increases in proportion to size of list. ðOn average, half the list must be shifted up or down to add or remove. ðclient must have a good idea of the ultimate size of a list _Choosing a size that is too large will waste space; _choosing a size too small will cause the program to fail.

35May 2004NH-Chapter 13 Dynamic lists ñTwo types of list implementations: ñBounded: set a maximum list size, ñDynamic: no list size upper bound.

36May 2004NH-Chapter 13 Dynamic lists ñTo implement a dynamic list solution using arrays, which have fixed size, create a larger array when necessary. private void makeRoom () { if (this.size == elements.length) { // need a bigger array, so make one twice as big Object[] newArray = new Object[2*elements.length]; // copy contents of old array to new for (int i = 0; i < elements.length; i = i+1) newArray[i] = elements[i]; elements = newArray; // replace old array with new }

37May 2004NH-Chapter 13 Dynamic list  Disadvantage: add operation can be expensive.  The add(Element) method invokes make room : public void add (Element element) { makeRoom(); elements[size] = element; size = size+1; }

38May 2004NH-Chapter 13 Implementing a Dynamic list: DefaultList ñjava.util.Vector ñcontains an Object array. ñVector add() replaces array with larger one when needed. ñjava.util.Vector ñprovides the List functionality required. ñBut Vector interface is different to List interface.

39May 2004NH-Chapter 13 Implementing a Dynamic list: DefaultList ñadapt (wrap) Vector ñDefaultList Implementation has Vector component ñDefaultList will extend AbstractList.

40May 2004NH-Chapter 13 AbstractList DefaultList adaptee java.util.Vector Static diagram for DefaultList List «interface»

41May 2004NH-Chapter 13 DefaultList implementation public class DefaultList extends AbstractList { private java.util.Vector elements; public DefaultList () { this.elements = new java.util.vector (); } public int size () { return this.elements.size(); } public Element get (int index) { return this.elements.get(index); }

42May 2004NH-Chapter 13 DefaultList implementation public void add (int index, Element element) { this.elements.add(index,element); } public void remove (int index) { this.elements.removeElementAt(index); } public void set (int index, Element element) { this.elements.setElementAt(element,index); }

43May 2004NH-Chapter 13 DefaultList implementation public DefaultList copy () { DefaultList copy = new DefaultList (); int i = 0; while (i < this.size()) { copy.add(this.get(i)); i = i+1; } return copy; } }//end of DefaultList

44May 2004NH-Chapter 13 Summary ñExamined Java’s array classes. ñAn array is a primitive structure that consists of a contiguous sequence of variables, all of the same type. ñArray component can be a primitive type or a reference type. ñAccess to an array element requires only constant time, independent of the size of the array. ñArray constructor requires integer specifying size of array. ñArray size is fixed once the array is created.

45May 2004NH-Chapter 13 Summary ñUsed Object arrays to implement a variation of the interface List : BoundedList. ñThe array is used to store the elements of the list.  Methods get(int), set(int,Element), and add(Element) require constant time to execute.  Methods add(int,Element) and remove(int), are linear. ñNumber of steps required, on average, increases in proportion to the size of the list.

46May 2004NH-Chapter 13 Summary  Considered several variations of copy method. ñShallow copy: copies instance variable values from the original object to the copy. ñIf an object references another component object by means of an instance variable, both the object and its copy will reference the same component object. ñDeep copy: copies the component objects rather than just reference values.

47May 2004NH-Chapter 13 Summary  Considered Object method clone and how a class “turns on” the cloning facility by implementing the interface Cloneable.  Method clone should produce a different object equal to, and of same class as, the cloned object.

48May 2004NH-Chapter 13 Summary ñConsidered an approach to solve the fixed size limitation of BoundedList. ñcreate a new, larger array to hold list elements when the existing array is filled. ñThe Java class java.util.Vector used to build DefaultList takes this approach. ñElements are stored in an array. When an element is added to the Vector and there is no room in the array, a new, larger array is created. Elements are copied from the old array to the new.