Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 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

2 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.

3 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.

4 3May 2004NH-Chapter 13 Anatomy of an array 0 2 1 3 4 5 7 9 8 6 10 11 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.

5 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

6 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.

7 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.

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

9 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;

10 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);

11 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;

12 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.

13 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.

14 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.

15 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.

16 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))

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

18 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

19 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);

20 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.

21 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.

22 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; }

23 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; }

24 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; }

25 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.

26 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; }

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

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

29 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

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

31 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();

32 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 { };

33 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.

34 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)

35 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.

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

37 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 }

38 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; }

39 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.

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

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

42 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); }

43 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); }

44 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

45 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.

46 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.

47 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.

48 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.

49 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.


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

Similar presentations


Ads by Google