vectors cmput 115 - lecture 4 department of computing science university of alberta ©duane szafron...

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

Post on 21-Dec-2015

214 views

Category:

Documents


1 download

TRANSCRIPT

VectorsVectors

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

©Duane Szafron 1999

2

About This LectureAbout 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.

©Duane Szafron 1999

3

OutlineOutline

Motivation

Scalable programs and containers

The limitations of Arrays

Using Vectors

Implementing Vectors

©Duane Szafron 1999

4

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

©Duane Szafron 1999

5

x

What’s a Vector?What’s a Vector?

Quantity having both magnitude and direction. Velocity vector

y

z

dx

How can a velocityvector be represented?

(magnitude,direction) (100 km/hr, <dx,dy,dz>) “vectorization” =>

“linearization”

©Duane Szafron 1999

6

What’s a Vector data structure?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.

©Duane Szafron 1999

7

Examples Vectors?Examples Vectors?

Represent single-valued relations (functions):

f(n) = 2n + 3

f(n) = n2

f(n) = n3 + n2 + 2n - 3

1 2 3 4 5n

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)

©Duane Szafron 1999

8

Limitations of Named VariablesLimitations 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; . . .

©Duane Szafron 1999

9

ContainersContainers

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.

©Duane Szafron 1999

10

Indexed ContainersIndexed 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"

©Duane Szafron 1999

11

ArraysArrays

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"

©Duane Szafron 1999

12

Array Fixed Size Limits ScalabilityArray 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 characterswhile (!aStream.eof()) { // check for end of file

data[index] = aStream.readString();index++;aStream.skipWhite() }

©Duane Szafron 1999

13

User Specified Array SizeUser 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.

©Duane Szafron 1999

14

VectorsVectors

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"

©Duane Szafron 1999

15

Java VectorsJava 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 characterswhile (!aStream.eof()) { // check for end of file

aString = aStream.readString();data.addElement(aString);aStream.skipWhite();

}

code based on Bailey pg. 33

©Duane Szafron 1999

16

Vector Interface Vector Interface 11

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

©Duane Szafron 1999

17

Vector Interface Vector Interface 22

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

©Duane Szafron 1999

18

Vector Interface 3Vector 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

©Duane Szafron 1999

19

Example - Word Frequencies Example - Word Frequencies 11

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

©Duane Szafron 1999

20

RequirementsRequirements

Build Vocabulary (including frequency counter)

Display the wordfrequencies

this isa

sampleinput

streamit

can...

13111121...

This is a sample input stream. It can be used to test thatwe are creating the vocabulary vector correctly. Big is big and little is it. .....

Input Stream

Association

©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 characterswhile (!aStream.eof()) { // check for end of file

word = aStream.readString();countWord(word, vocabulary);aStream.skipWhite();

Example - Word Frequencies Example - Word Frequencies 22

code based on Bailey pg. 35vocabulary

aStream

word1word2word3

©Duane Szafron 1999

22

Example - Word Frequencies Example - Word Frequencies 33

private static void countWord(String word, Vector vocabulary){

/* pre: a non-null String word and a Vector of Associations vocabularypost: 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 vocabularyvocabulary.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

©Duane Szafron 1999

23

Example - Word Frequencies Example - Word Frequencies 44

private static Association getEntry(String word, Vector vocabulary){

/* pre: a non-null String and a Vector of Associationspost: 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. . .

key frequency

key frequency

vocabulary Vector

©Duane Szafron 1999

24

Example - Word Frequencies Example - Word Frequencies 55

private static void displayFrequencies(Vector vocabulary){/*

pre: vocabulary is a Vector of Associationspost: 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

©Duane Szafron 1999

25

Implementing Java ContainersImplementing 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

©Duane Szafron 1999

26

Vector Implementation StrategyVector 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.

aVectorelementData

elementCount“Fred” “Wilma” null null

anArray0 1 2 3

2

©Duane Szafron 1999

27

Vector Instance VariablesVector 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

©Duane Szafron 1999

28

Vector ConstructorsVector 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

©Duane Szafron 1999

29

Vector SizeVector 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

©Duane Szafron 1999

30

Vector Element AccessingVector 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!

©Duane Szafron 1999

31

Vector Element AddingVector 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

©Duane Szafron 1999

32

Vector Insertion StrategyVector 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.

©Duane Szafron 1999

33

Vector Insertion ExampleVector Insertion Example

For example, insert “Wilma” at index 1.

aVectorelementData

elementCount 3

anArray0 1 2 3

“Fred” “Barney” “Betty” null

“Wilma”

34

4 12

©Duane Szafron 1999

34

Vector Insertion CodeVector 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

©Duane Szafron 1999

35

Vector Removal StrategyVector 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.

©Duane Szafron 1999

36

Vector Removal ExampleVector Removal Example

For example, remove “Wilma” at index 1.

aVectorelementData

elementCount

anArray0 1 2 3

“Fred” “Wilma” “Barney” “Betty”

42 4

null3

1 3

©Duane Szafron 1999

37

Vector Removal CodeVector 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

©Duane Szafron 1999

38

Vector Growth StrategyVector 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.

©Duane Szafron 1999

39

Example Vector GrowthExample Vector Growth

Add the string “Pebbles” to a vector with logical and physical size 4.

a VectorelementData

elementCount

old Array0 1 2 3

“Fred” “Wilma” “Barney” “Betty”4

new Array0 1 2 3

“Pebbles” null null null

4 5 6 75

One more thing to do?

©Duane Szafron 1999

40

Vector Growth Amount Vector Growth Amount 11 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.

©Duane Szafron 1999

41

Vector Growth Amount Vector Growth Amount 22

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

©Duane Szafron 1999

42

Specifying a Growth AmountSpecifying a Growth Amount We add an instance variable and constructor:

protected int capacityIncrement; // zero means doublingpublic 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

©Duane Szafron 1999

43

Vector Growth Code 1Vector Growth Code 1public void ensureCapacity(int minCapacity) { //private?//post: the capacity is at least the given value

Object newElementData[ ];int newLength;int index;

if this.elementData.length >= minCapacityreturn;

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

©Duane Szafron 1999

44

Vector Growth Code 2Vector Growth Code 2private 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 capacityif (newLength == 0) newLength = 1;while (newLength < minCapacity)newLength = newLength * 2;elsewhile (newLength < minCapacity)newLength += this.capacityIncrement;return newLength; }

code based on Bailey pg. 42

©Duane Szafron 1999

45

Principles from the TextbookPrinciples from the Textbook

6. Maintaining a consistent

interface makes a

structure useful.

principles from Bailey ch. 3

©Duane Szafron 1999

46

0123

. . .1000

What are we doing?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

Thisis

adata[0] ”This”data[1] “is”data[2] “a”. . . data[13] “keyboard”

declare aStream to bea ReadStream

INPUT

Data[0->999]