unit 5 1 arrays and vectors h arrays and vectors are objects that help us organize large amounts of...

40
1 unit 5 Arrays and Vectors Arrays and Vectors Arrays and vectors are objects that help us organize large amounts of information We will talk about: array declaration and use arrays of objects multidimensional arrays the Vector class basic programmin g concepts object oriented programmin g topics in computer science syllabus

Post on 22-Dec-2015

227 views

Category:

Documents


0 download

TRANSCRIPT

1unit 5

Arrays and VectorsArrays and Vectors

Arrays and vectors are objects that help us organize large amounts of information

We will talk about:• array declaration and use• arrays of objects• multidimensional arrays• the Vector class

basic programming

concepts

object oriented programming

topics in computer science

syllabus

2unit 5

ArraysArrays

An array is an ordered list of values

0 1 2 3 4 5 6 7 8 9

79 87 94 82 67 98 87 81 74 91

An array of size N is indexed from zero to N-1An array of size N is indexed from zero to N-1

scores

The entire arrayThe entire arrayhas a single namehas a single name

Each value has a numeric Each value has a numeric indexindex

This array holds 10 values that are indexed from 0 to 9This array holds 10 values that are indexed from 0 to 9

3unit 5

Refering to Array ElementsRefering to Array Elements

A particular value in an array is referenced using the array name followed by the index in brackets

For example, the expression scores[2]

refers to the value 94 (the 3rd value in the array)

scores[2] represents a place to store a single integer, and can be used wherever an integer variable can

For example, it can be assigned a value, printed, or used in a calculation

4unit 5

Array TypeArray Type

An array stores multiple values of the same type, primitive types or objects. Examples: an array of integers, an array of characters, an array of String objects

In Java, the array itself is an object. Therefore the name of the array is a object reference variable, and the array itself is instantiated separately

5unit 5

Array DeclarationArray Declaration

The scores array could be declared as follows:

int[] scores = new int[10];

Note that the type of the array does not specify its size, but each object of that type has a specific size

The type of the variable scores is int[] (an array of integers)

It is set to a new array object that can hold 10 integers

6unit 5

public class BasicArray{

final static int LIMIT = 15; final static int MULTIPLE = 10;

--------------------------------------------------//

// Creates an array, fills it with integer values, // modifies one value, then prints them out.

----------------------------------------------------// public static void main (String[] args)

{ int[] list = new int[LIMIT];

0 1 2 3 4 ... 11 12 13 14

list

זכרון

7unit 5

public class BasicArray{

final static int LIMIT = 15; final static int MULTIPLE = 10;

--------------------------------------------------//

// Creates aan rray, fills it with integer values, // modifies one value, then prints them out.

----------------------------------------------------// public static void main (String[] args)

{ int[] list = new int[LIMIT];

//Initialize the array values for (int index = 0; index < LIMIT; index++)

list[index] = index * MULTIPLE;

0 10 20 30 40 ... 110 120 130 140list

0 1 2 3 4 ... 11 12 13 14זכרון

8unit 5

public class BasicArray{

final static int LIMIT = 15; final static int MULTIPLE = 10;

--------------------------------------------------//

// Creates aan rray, fills it with integer values, // modifies one value, then prints them out.

----------------------------------------------------// public static void main (String[] args)

{ int[] list = new int[LIMIT];

//Initialize the array values for (int index = 0; index < LIMIT; index++)

list[index] = index * MULTIPLE;

0 1 2 3 4 ... 11 12 13 14

0 10 20 30 40 ... 110 120 130 140

0 10 20 30 99 50 60 70 80 90 100 110 120 130 140

for (int index = 0; index < LIMIT; index++) System.out.print (list[index] + " ") ;

System.out.println;() } }

list[4] = 99; // change one array value

99list

זכרון

מסך

9unit 5

Examples of array declarationsExamples of array declarations::

float[] prices = new float[500];

boolean[] flags;

flags = new boolean[20];

char[] codes = new char[1750];

10unit 5

Bounds CheckingBounds Checking

Once an array is created, it has a fixed size

An index used in an array reference must specify a valid element: value must be within bounds (0 to N-1)

The Java interpreter will detect an error if an array index is out of bounds; this is called automatic bounds checking

11unit 5

Bounds CheckingBounds Checking

For example, if the array codes can hold 100 values, it can only be indexed using the numbers 0 to 99

If count has the value 100, the Jave interpretter will give the message “Array Out Of Bounds”

It’s common to introduce off-by-one errors when using arrays:

int[] codes = new int[100];for (int index=1; index <= 100; index++)

codes[index] = index*50 + epsilon;

problem

12unit 5

Number of array elementsNumber of array elements

Each array object has a public constant called length that stores the size of the array

It is referenced using the array name (just like any other object):

scores.length

Note that length holds the number of elements, not the largest index

13unit 5

//ReverseNumbers.java

public class ReverseNumbers{-----------------------------------------------------------------//

// Reads a list of numbers from the user, storing them in an // array, then prints them in the opposite order.

-----------------------------------------------------------------// public static void main (String[] args)

{

System.out.println;()

} }

double[] numbers = new double[10];

System.out.println ("The size of the array: " + numbers.length);

for (int index = 0; index < numbers.length; index++) numbers[index] = EasyInput.getDouble("Enter next number");

System.out.println ("The numbers in reverse:");

for (int index = numbers.length-1; index >= 0; index--) System.out.print (numbers[index] + " ");

14unit 5

Array Declarations RevisitedArray Declarations Revisited

The brackets of the array type can be associated with the element type or with the name of the array

Therefore the following declarations are equivalent:

float[] prices;

float prices[];

The first format is generally more readable

15unit 5

Shortcut: Initializer ListsShortcut: Initializer Lists

An initializer list can be used to instantiate and initialize an array in one step

The values are delimited by braces and separated by commas

Examples: int[] units = {147, 323, 89, 933, 540,

269, 97, 114, 298, 476};

char[] letterGrades = {'A', 'B', 'C', 'D', 'F'};

16unit 5

Initializer ListsInitializer Lists

Note that when an initializer list is used:• the new operator is not used

• no size value is specified

The size of the array is determined by the number of items in the initializer list

An initializer list can only be used in the declaration of an array

17unit 5

Arrays of ObjectsArrays of Objects

The elements of an array can be object references

The following declaration reserves space to store 25 references to String objects

String[] words = new String[25];

It does not create the String objects themselves

Each object stored in an array must be instantiated separately

18unit 5

//GradeRange.java

public class GradeRange{-----------------------------------------------------------------//

// Stores the possible grades and their numeric lowest value, // then prints them out.

-----------------------------------------------------------------// public static void main (String[] args)

{ String[] grades = }"A", "A-", "B+", "B", "B-", "C+", "C", "C,"-

" D+", "D", "D-", "F;}"

int[] cutoff = }95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0{;

for (int level = 0; level < cutoff.length; level++) System.out.println (grades[level] + "\t" + cutoff[level]);

} }

A 95

A- 90

B+ 87

B 83

B- 80

C+ 77

C 73

C- 70

D+ 67

D 63

D- 60

F 0

19unit 5

A

A

B

-

String[] grades

{

Organizing array of objects in memoryOrganizing array of objects in memory

20unit 5

Array of objectsArray of objects

Coin[] dimes = new Coin[10];

int face;

face = dimes[1].getFace(); Xdimes[1] = new Coin(); face = dimes[1].getFace();

21unit 5

Command-Line ArgumentsCommand-Line Arguments

The signature of the main method indicates that it takes an array of String objects as a parameter

public static void main (String[] args)

These values come from command-line arguments that are provided when the interpreter is invoked

For example, the following invocation of the interpreter passes an array of three String objects into main:

> java VoteRecount Florida New-Mexico Oregon

These strings are stored in args[0], args[1] and args[2] respectively

22unit 5

Array members of ObjectsArray members of Objects

Objects can have arrays as instance variables

Therefore, fairly complex structures can be created simply with arrays and objects

The software designer must carefully determine an organization of data and objects that makes sense for the situation

23unit 5

Arrays as ParametersArrays as Parameters

A reference to an array can be passed to a method as a parameter

Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other

As the method access the array through an alias reference, the content of the array can be changed

An array element can be passed to a method like any other value

24unit 5

Example: class PolynomExample: class Polynom

// A polynom is a real valued function of the

// form f(x)=a0+a1x+a2x2+...+anxn. public class Polynom { // The coefficients of the polynom // coefficients[i] is the coefficient of xi

private double[] coefficients;

// Constructs a polynom with a given set // of coefficients. public Polynom(double[] coefficients) { this.coefficients = new double[coefficients.length]; for (int i=0; i<coefficients.length; ++i)

this.coefficients[i] = coefficients[i]; }

25unit 5

Class Polynom service method 1Class Polynom service method 1

// Computes the value of the polynom for given point

// @return: the value of the polynom at x

public double valueAt(double x) {

double value = 0.0;

double power = 1.0;

for (int i=0; i<coefficients.length; i++) {

value += coefficients[i]*power;

power *= x;

}

return value;

}

26unit 5

Class Polynom service method 2Class Polynom service method 2

// Returns the degree of the polynom

public int getDegree() {

int degree = coefficients.length-1;

while (coefficients[degree]==0.0) {

degree--;

}

return degree;

}

27unit 5

Class Polynom service method 3Class Polynom service method 3// Computes the polynom resulting from the addition// of this polynom and another polynom.public Polynom add(Polynom p) {

return new Polynom(coeffs);}}

int degree = Math.max(getDegree(), p.getDegree());

int degmin = Math.min(getDegree(), p.getDegree());

double[] coeffs = new double[degree];

for (int i=0; i<degmin; i++)

coeffs[i] = coefficients[i] + p.coefficients[i];

for (int i=degmin; i<degree; i++)

if (getDegree()<p.getDegree())

coeffs[i] = coefficients[i];

else

coeffs[i] = p.coefficients[i];

28unit 5

Using class polynomUsing class polynom

// Prints a table of values for x3-2x2+5x+7;

class PolynomUseExample {

static final double LOWER_LIMIT = -5.0;

static final double UPPER_LIMIT = 5.0;

static final double STEP = 1.0;

public static void main(String[] args) {

double[] coefficients = {7.0, 5.0, -2.0, 1.0};

Polynom p = new Polynom(coefficients);

for (double x=LOWER_LIMIT; x<=UPPER_LIMIT; x+=STEP)

System.out.println(x + ” \t “ + p.valueAt(x));

}

}

29unit 5

Two-Dimensional ArraysTwo-Dimensional Arrays

A one-dimensional array stores a simple list of values

A two-dimensional array can be thought of as a table of values, with rows and columns

A two-dimensional array element is referenced using two index values

To be precise, a two-dimensional array in Java is an array of arrays

30unit 5

Array of arraysArray of arrays

double[][] samples;

samples = new double[6][];

samples[0] = new double[2];

samples[1] = new double[1];

for (int i=2; i<samples.length; i++)

samples[i] = new double[i+1];

31unit 5

class Table2D { public static void main(String[] args) { int[][] table2D = new int[4][]; table2D[0] = new int[7]; table2D[1] = new int[6]; table2D[2] = new int[8]; table2D[3] = new int[7]; for (int j=0; j<table2D.length; j++) {

for (int i=0; i<table2D[j].length; i++) System.out.print(table2D[j][i]); System.out.println();

} } }

47

6

8

7

32unit 5

Two dimensional arrayTwo dimensional array

double[][] samples;

samples = new double[6][6];

33unit 5

Example: class MatrixExample: class Matrix

// A matrix of real numberspublic class Matrix { // The elements of the matrix private double[][] elements;

// Construct new matrix from table of values public Matrix(double[][] elements) {

int height = elements.length;int width = elements[0].length;this.elements = new double[height][width];for (int i=0; i<height; ++i)

for (int j=0; j<width; ++j)this.elements[i][j] = elements[i][j];

}}

34unit 5

Class Matrix service methodsClass Matrix service methods

// Returns the number of rows of the matrixpublic int numberOfRows() { return elements.length;}

// Returns the number of columns of the matrixpublic int numberOfColumns() { return elements[0].length;}

// Returns element (i,j) of the matrixpublic double getElement(int i, int j) {

return elements[i][j];}

35unit 5

Class Matrix service methodsClass Matrix service methods

public Matrix multiply(Matrix a) { int n = numberOfRows(); int m = numberOfColumns(); int l = a.numberOfColumns(); double[][] result = new double[n][l]; for (int i=0; i<n; i++) { for (int j=0; j<l; j++) { for (int k=0; k<m; k++) { result[i][j] += elements[i][k]*a.elements[k][j]; } } } return new Matrix(result);}

36unit 5

Example: using class matrixExample: using class matrix

class MatrixUse {

public static void main(String[] args) {

double[][] aElements = {

{ 1.0, 2.0},

{-3.0, 1.0}

};

double[][] bElements = {

{ 3.0,-1.0},

{-2.0, 2.0}

};

37unit 5

Example: using class matrixExample: using class matrix

Matrix a,b,c; a = new Matrix(aElements); b = new Matrix(bElements); c = a.multiply(b);

for (int i=0; i<c.numberOfRows(); i++) { for (int j=0; j<c.numberOfColumns(); j++) { System.out.print(c.getElement(i,j)+” ”); } System.out.println(); } }}

38unit 5

Multidimensional ArraysMultidimensional Arrays

An array can have as many dimensions as needed, creating a multidimensional array

Each dimension subdivides the previous one into the specified number of elements

Each array dimension has its own length member

Because each dimension is an array of array references, the arrays within one dimension could be of different length

39unit 5

The The VectorVector Class Class

An object of class Vector is similar to an array in that it stores multiple values

However, a vector• only stores objects• does not have the indexing syntax that arrays have

The methods of the Vector class are used to interact with the elements of a vector

The Vector class is part of the java.util package

See Beatles.java (page 304)

40unit 5

The The VectorVector Class Class

An important difference between an array and a vector is that a vector can be thought of as a dynamic, able to change its size as needed

Each vector initially has a certain amount of memory space reserved for storing elements

If an element is added that doesn't fit in the existing space, more room is automatically acquired