Presentation is loading. Please wait.

Presentation is loading. Please wait.

Vectors Cmput 115 - Lecture 4 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

Similar presentations


Presentation on theme: "Vectors Cmput 115 - Lecture 4 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from."— Presentation transcript:

1 Vectors Cmput 115 - Lecture 4 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from the book: Java Structures by Duane A. Bailey or the companion structure package Revised 1/3/2000

2 ©Duane Szafron 1999 2 About This Lecture In this lecture we will learn how to use and implement the Vector class. A Vector is a collection object that can change its size as elements are added and removed.

3 ©Duane Szafron 1999 3Outline Motivation Scalable programs and containers The limitations of Arrays Using Vectors Implementing Vectors

4 ©Duane Szafron 1999 4 Scalable Applications When an application is run several times, the amount of data it must represent can vary. For some applications, the amount of data that must be represented can vary as the application is running. An application that works with a variable amount of data is said to be scalable. A program represents data by objects with values and accesses this data using references like variables and literals.

5 ©Duane Szafron 1999 5 x What’s a Vector? Quantity having both magnitude and direction. Velocity vector y z dx How can a velocity vector be represented? (magnitude,direction) (100 km/hr, ) “vectorization” => “linearization”

6 ©Duane Szafron 1999 6 What’s a Vector data structure? A Vector is a collection object that can change its size as elements are added and removed. A Vector has a rank order, i.e, its elements can be indexed by 0, 1, 2, 3,... => linear structure (grows in one-dimension) as opposed to an array which can have two or more dimension. In older languages (e.g., FORTRAN) vector == one-dimensional array In Java a vector can change its size. Makes them very good for “scalable” problems.

7 ©Duane Szafron 1999 7 Examples Vectors? Represent single-valued relations (functions): f(n) = 2n + 3 f(n) = n 2 f(n) = n 3 + n 2 + 2n - 3 1 2 3 4 5 n f(n) 5 10 15 (3, 5, 7, 9, 11, 13) (0, 1, 4, 9, 16, 15) Represent general relations: - e.g., days in the month (31, 28, 31, 30, 31, 30,..., 31) - GPA for each year in university: (6.7, 7.2, 7.1, 7.7)

8 ©Duane Szafron 1999 8 Limitations of Named Variables Named variables and literals are not sufficient to build a scalable program. code based on Bailey pg. 31 For example, here is a program that remembers two words: String string1; String string2; ReadStream aStream; aStream = new ReadStream(); // a read Stream on the keyboard string1 = aStream.readString(); // read a space-delimited word string2 = aStream.readString(); If we want to read more words we would need to add variables and re-compile the program. String string3; String string4; String string5;...

9 ©Duane Szafron 1999 9Containers An object’s state consists of instance variables that are bound to objects or values. It is useful to have objects whose state includes an arbitrary number of objects. An object that remembers an arbitrary number of other objects is called a container or a collection. Containers are necessary to build scalable programs.

10 ©Duane Szafron 1999 10 Indexed Containers Containers whose elements are indexed by integers are called indexed containers. The integer indexes are the object references. 0 1 2 3... "Fred""Barney""Wilma" "Betty"

11 ©Duane Szafron 1999 11Arrays Arrays are containers that hold a fixed number of elements. Depending on the language, the size must be specified at compile time (Pascal) or run-time (Java). 0 1 2 3 "Fred""Barney""Wilma" "Betty" 0 1 2 3... "Fred""Barney""Wilma" "Betty"

12 ©Duane Szafron 1999 12 Array Fixed Size Limits Scalability This fixed size, limits scalability. One option (in Pascal or Java) is to fix a maximum size before the computation begins: code based on Bailey pg. 32 String data[ ]; ReadStream aStream; int index; final int size = 1000; aStream = new ReadStream(); // a read Stream on the keyboard data = new String[size]; index = 0; aStream.skipWhite(); // skip all white space characters while (!aStream.eof()) { // check for end of file data[index] = aStream.readString(); index++; aStream.skipWhite() }

13 ©Duane Szafron 1999 13 User Specified Array Size In Java, another option is to require the user to specify the size: code based on Bailey pg. 32 String data[ ]; ReadStream aStream; int index; aStream = new ReadStream(); // read Stream on the keyboard size = aStream.readInt(); // the number of Strings to be read data = new String[size]; for (index = 0; index < size; index++) data[index] = aStream.readString(); Although this code is scalable, it is not always possible to determine a size before a computation begins.

14 ©Duane Szafron 1999 14Vectors A Vector is an indexed container whose size changes as elements are added and removed. 0 1 2 "Fred""Barney""Wilma" 0 1 2 3 "Fred""Barney""Wilma" "Betty"

15 ©Duane Szafron 1999 15 Java Vectors Java has a class called Vector that can hold objects but not values. Vector data; ReadStream aStream; aStream = new ReadStream(); // a read Stream on the keyboard data = new Vector(); aStream.skipWhite(); // skip all white space characters while (!aStream.eof()) { // check for end of file aString = aStream.readString(); data.addElement(aString); aStream.skipWhite(); } code based on Bailey pg. 33

16 ©Duane Szafron 1999 16 Vector Interface 1 Here is a partial interface for the Vector class: public class Vector implements Cloneable { public Vector() // post: constructs an empty vector public Vector(int initialCapacity) //pre: initialCapacity >= 0 //post: constructs an empty vector with given initial space public void addElement(Object object) //post: adds the given element to the end code based on Bailey pg. 36 0... iC-1

17 ©Duane Szafron 1999 17 Vector Interface 2 public Object elementAt(int index) //pre: 0 <= index < size() //post: returns the element stored in the given location public void insertElementAt(Object object, int index) //pre: 0 <= index <= size() //post: inserts the given object at the given index, // moving elements from index to size()-1 to the right. public boolean isEmpty() //post: returns true if there are no elements in the vector public boolean removeElement(Object element) //post: the given element is removed from the vector code based on Bailey pg. 36

18 ©Duane Szafron 1999 18 Vector Interface 3 public void removeElementAt(int index) //pre: 0 <= index < size() //post: the element at the given index is removed and all // elements from index to size()-1 are moved to the left public void setElementAt(Object object, int index) //pre: 0 <= index < size() //post: the element at the given index is changed to the // given object public int size() //post: returns the size of the vector code based on Bailey pg. 36

19 ©Duane Szafron 1999 19 Example - Word Frequencies 1 public static void main(String args[]) throws IOException { /* This program counts the frequencies of words from the input. */ Vector vocabulary; vocabulary = buildVocabulary(); displayFrequencies(vocabulary); } code based on Bailey pg. 35

20 ©Duane Szafron 1999 20Requirements Build Vocabulary (including frequency counter) Display the word frequencies this is a sample input stream it can... 1 3 1 2 1... This is a sample input stream. It can be used to test that we are creating the vocabulary vector correctly. Big is big and little is it...... Input Stream Association

21 ©Duane Szafron 1999 21 private static Vector buildVocabulary() throws IOException { /* post: returns a vector of word-frequency associations from the input */ } return vocabulary; } Vector vocabulary; ReadStream aStream; String word; aStream = new ReadStream(new FileInputStream(new File(“data.txt”))); vocabulary = new Vector(); aStream.skipWhite(); // skip all white space characters while (!aStream.eof()) { // check for end of file word = aStream.readString(); countWord(word, vocabulary); aStream.skipWhite(); Example - Word Frequencies 2 code based on Bailey pg. 35 vocabulary aStream word 1 word 2 word 3

22 ©Duane Szafron 1999 22 Example - Word Frequencies 3 private static void countWord(String word, Vector vocabulary){ /* pre: a non-null String word and a Vector of Associations vocabulary post: update the frequency count of the given word in the given Vector of word-frequency Associations. If the word is not in any of the Associations add a new Association for it. */ Association entry; Integer frequency; entry = getEntry(word, vocabulary); if (entry == null) //entry is not in vocabulary vocabulary.addElement(new Association(word, new Integer(1))); else { frequency = (Integer) entry.value(); entry.setValue(new Integer(frequency.intValue() + 1)) } code based on Bailey pg. 35

23 ©Duane Szafron 1999 23 Example - Word Frequencies 4 private static Association getEntry(String word, Vector vocabulary){ /* pre: a non-null String and a Vector of Associations post: return the Association in the Vector of Associations with the given String as its key. If the String is not in any of the Associations return null. */ Association entry; int index; String aString; for (index = 0; index < vocabulary.size(); index++) { entry = (Association) vocabulary.elementAt(index); aString = (String) entry.key(); if (aString.equals(word)); return entry; } return null; } code based on Bailey pg. 35 entry index Association... keyfrequency keyfrequency vocabulary Vector

24 ©Duane Szafron 1999 24 Example - Word Frequencies 5 private static void displayFrequencies(Vector vocabulary){ /* pre: vocabulary is a Vector of Associations post: display the words and their frequencies from the given vocabulary. */ Association entry; int index; for (index = 0; index < vocabulary.size(); index++) { entry = (Association) vocabulary.elementAt(index); System.out.println(entry.key() + “ occurs “ + entry.value() + “ times.”); } code based on Bailey pg. 35

25 ©Duane Szafron 1999 25 Implementing Java Containers The Array is the only container that is pre-defined in the Java language. All user-defined containers must be implemented using basic Array objects, a technique called self- reference (to be described later) or other user- defined containers. code based on Bailey pg. 33

26 ©Duane Szafron 1999 26 Vector Implementation Strategy We will implement vectors using arrays: –Each vector has two instance variables: one bound to an array with a fixed physical [size] entity and one bound to a logical size. –Instance variables of the array that are not being used are at the right side and are bound to null. aVector elementData elementCount “Fred”“Wilma”null anArray 0123 2

27 ©Duane Szafron 1999 27 Vector Instance Variables The instance variables are declared as protected so they can be accessed in future subclasses. public class Vector implements Cloneable { /* Instance Variables */ protected Object elementData[ ]; // physical storage protected int elementCount; //logical size code based on Bailey pg. 38

28 ©Duane Szafron 1999 28 Vector Constructors The user can provide an initial capacity for the “expected” size of a Vector. /* Constructors */ public Vector() { // post: constructs an empty vector this(10); // constructor chaining} public Vector(int initialCapacity) //pre: initialCapacity >= 0 //post: constructs an empty vector with given initial space Assert.pre(initialCapacity >=0,“Nonnegative capacity.”); this.elementData = new Object[initialCapacity]; this.elementCount = 0; } code based on Bailey pg. 38

29 ©Duane Szafron 1999 29 Vector Size The logical size of a vector: –is “cached” in elementCount for fast access. –However, the value of elementCount must be updated whenever the size changes. public int size() { //post: returns the size of the vector return this.elementCount; } public boolean isEmpty() { //post: returns true if there are no elements in the vector return (this.size() == 0); } code based on Bailey pg. 41

30 ©Duane Szafron 1999 30 Vector Element Accessing The vector indexes correspond to the array indexes: /* Instance Methods */ public Object elementAt(int index) { //pre: 0 <= index < size() //post: returns the element stored in the given location return elementData[index]; } public void setElementAt(Object object, int index) { //pre: 0 <= index < size() //post: the element at the given index is changed to the given object elementData[index] = object; } code based on Bailey pg. 38 //it overwrites!

31 ©Duane Szafron 1999 31 Vector Element Adding Adding an element is easy if the logical size is less than the physical size: public void addElement(Object object){ //post: adds the given element to the end this.ensureCapacity(this.elementCount + 1); this.elementData[this.elementCount] = object; this.elementCount++; } code based on Bailey pg. 38

32 ©Duane Szafron 1999 32 Vector Insertion Strategy When an element is inserted at an index: –Ensure that the physical size is at least one larger than the logical size. –Rebind all indexes starting at the logical size and ending at one greater than the insertion index to the element whose index is one less. –Rebind the insertion index to the new element. –Increment the logical size.

33 ©Duane Szafron 1999 33 Vector Insertion Example For example, insert “Wilma” at index 1. aVector elementData elementCount 3 anArray 0123 “Fred”“Barney”“Betty”null “Wilma” 34 4 12

34 ©Duane Szafron 1999 34 Vector Insertion Code public void insertElementAt(Object object, int index) { //pre: 0 <= index <= size() //post: inserts the given object at the given index, // moving elements from index to size()-1 to the right int i; this.ensureCapacity(this.elementCount + 1); for (i = this.elementCount; i > index; i--) this.elementData[i] = this.elementData[i - 1]; this.elementData[index] = object; this.elementCount++; } code based on Bailey pg. 39

35 ©Duane Szafron 1999 35 Vector Removal Strategy When an element is removed at an index: –Decrement the logical size. –Rebind all indexes starting at the insertion index and ending at the logical size to the element whose index is one more. –There is no longer a reference to the element being removed. –Bind the index at elementCount to null.

36 ©Duane Szafron 1999 36 Vector Removal Example For example, remove “Wilma” at index 1. aVector elementData elementCount anArray 0123 “Fred”“Wilma”“Barney”“Betty” 4 2 4 null 3 1 3

37 ©Duane Szafron 1999 37 Vector Removal Code public void removeElementAt(int index) //pre: 0 <= index < size() //post: the element at the given index is removed and all // elements from index to size()-1 are moved to the left this.elementCount--; while (index < this.elementCount) { this.elementData[index] = this.elementData[index+1]; index++; } this.elementData[this.elementCount] = null; } code based on Bailey pg. 39

38 ©Duane Szafron 1999 38 Vector Growth Strategy When a vector’s array is full and another element is added to the vector: –A new larger array is created. –The initial range of the instance variables of the new array are bound to the existing elements of the old array (elements are not actually copied). –The new element is added to the new array (updating the logical size). –The old array object is free for storage reclamation.

39 ©Duane Szafron 1999 39 Example Vector Growth Add the string “Pebbles” to a vector with logical and physical size 4. a Vector elementData elementCount old Array 0123 “Fred”“Wilma”“Barney”“Betty” 4 new Array 0123 “Pebbles”null 4567 5 One more thing to do?

40 ©Duane Szafron 1999 40 Vector Growth Amount 1 There are several options: –Grow one element at a time Doesn’t waste any space directly. Requires extra indirect space as many arrays may be created and destroyed. Extra time required because of frequent extensions. –Increment by a fixed amount Requires less array manipulation time than single element growth. Not scalable since small vectors will have more space than they need and large ones will still require many allocations.

41 ©Duane Szafron 1999 41 Vector Growth Amount 2 –Double the size Faster since it requires less array manipulation. Is scalable since vectors that grow quickly receive a proportional amount of space. Could be unlucky, e.g. if vector requires 1025 elements and must allocate 2048 elements. –Let the programmer choose from all of these Less chance of being unlucky assuming the programmer knows something about the potential sizes of the vectors.

42 ©Duane Szafron 1999 42 Specifying a Growth Amount We add an instance variable and constructor: protected int capacityIncrement; // zero means doubling public Vector(int initialCapacity, int growthAmount) //pre: initialCapacity >= 0, growthAmount >= 0 //post: constructs an empty vector with given initial space // that grows by the given increment or doubles if it is 0 Assert.pre(initialCapacity >=0,“Nonnegative capacity.”); Assert.pre(growthAmount >=0,“Nonnegative growth.”); this.elementData = new Object[initialCapacity]; this.elementCount = 0; this.capacityIncrement = growthAmount; } We also modify the one argument constructor to set capacityIncrement to 0. code based on Bailey pg. 39

43 ©Duane Szafron 1999 43 Vector Growth Code 1 public void ensureCapacity(int minCapacity) { //private? //post: the capacity is at least the given value Object newElementData[ ]; int newLength; int index; if this.elementData.length >= minCapacity return; newLength = this.computeNewLength(minCapacity); newElementData[] = new Object[newLength]; for (index = 0; index < this.elementCount; index++) newElementData[index] = this.elementData[index]; this.elementData = newElementData; // storage of old array will be automatically reclaimed } code based on Bailey pg. 42

44 ©Duane Szafron 1999 44 Vector Growth Code 2 private int computeNewLength(int minCapacity) { //post: return the new length >= the given value and // consistent with the growth strategy int newLength; newLength = this.elementData.length; if (this.capacityIncrement == 0) { // double capacity if (newLength == 0) newLength = 1; while (newLength < minCapacity) newLength = newLength * 2; else while (newLength < minCapacity) newLength += this.capacityIncrement; return newLength; } code based on Bailey pg. 42

45 ©Duane Szafron 1999 45 Principles from the Textbook 6. Maintaining a consistent interface makes a structure useful. principles from Bailey ch. 3

46 ©Duane Szafron 1999 46 0 1 2 3... 1000 What are we doing? declare data to be vector of strings declare final to be int  1000 aStream  “ This is a sample set of text to be read from the keyboard” This is a sample set of text to be read from the keyboard This is a data[0]  ”This” data[1]  “is” data[2]  “a”... data[13]  “keyboard” declare aStream to be a ReadStream INPUT Data[0->999]


Download ppt "Vectors Cmput 115 - Lecture 4 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from."

Similar presentations


Ads by Google