Chapter 7 Arrays and Vectors

Download Report

Transcript Chapter 7 Arrays and Vectors

Chapter 5 Arrays and Vectors



An array allows you to group data items
together in a structure that is processed
via an index.
They allow you to process like data
items as a group.
Objects can also be stored in an array.
Array declarations and indices



An array is a data structure in which we
store a collection of data items of the
same type.
Arrays have a single variable name
associated with the entire collection.
Array of scores:
scores
88
95
33
67
85
Arrays




Arrays are stored in consecutive
memory locations in main memory.
We can pass entire arrays to methods
We can access the individual array
elements.
We can process the individual elements
like other simple variables.
Declaring arrays
Array
type
Array
name
Array
size
Double[] salary = new double[50];

Declares an array of type double that
can hold 50 values
Declaring arrays
Array
Type
Array
name
Array
Values
int[] coinValues = {1, 5, 10, 25, 50};

Alternative method to declare and
initialize array. What is the length of
the array?
Syntax Display
Form:
elementType[] arrayName = new elementType[size];
elementType[] arrayName = {list-of-values};
 arrayName represents a collection of array elements
each element can store an item of type elementType



The size maybe specified or calculated based on the
number of values in the list-of-values.
These items are stored sequentially.
elementType can be primitive type or class
Declaration versus Storage
allocation
You can declare an array and storage
separately.
double[] salary;
salary = new double[50];
 Why would you want to do this?

Processing array elements
An array index is used to process the
individual array elements.
 You use the array name and an index
displayResult(salary[1]);
 You can use this anywhere you would
use a value of that type.
 The index is either an integer or an
integer expression.

Indexed variable



When access array elements you start
at index 0 rather than 1.
salary[1] is called an indexed variable.
Salary is type double so we can use this
anywhere we use a double, arithmetic
operators, relational operators, the
assignment operator……..
Examples

Review example 5.1 on page 275 - 276


This uses literals as index
Review example 5.2 on page 276

This uses variables as the index
You must be assured that the variable is in
the valid range of index values.
• Out of bounds error
• Occurs at runtime
Section 5.2 processing arrays



For loops are typically used to process
an array
They allow you to process all elements
in an array in some way
Can be used to:



Enter data
Display contents
Perform other processing
Data field length





Java automatically allocates a data field
Length
Allocated for each array
Stores the array size in this data field
Can be used to process an array.
See code example 5.3 page 279
Example code
int[] example = new int[5];
for (int i = 0; i < example.length; i++)
example[i] = getInt("please enter an
integer");
for (int i = 4; i >= 0; i--)
displayResult(example[i]);
}
See code page 281 - 282

Calculates the cubes of numbers 1-10
Array cube example

First create array but does not set
length


private int[] cubes;
Then sets length of array via

cubes = new int[numCubes];
Array cube example

Fills the array via:



for (int i = 0; i < cubes.length; i++)
cubes[i] = i * i * i;
Calculates the sum of cubes:


for (int i = 0; i < cubes.length; i++)
sumCubes += cubes[i];
Array cube example

Displays results via



for (int i = 0; i < cubes.length; i++)
“glues” string together next
Look at running of example code.
Case Study Pages 283 - 289




Problem
Analysis
Design
Implementation
Operations on whole arrays
5.3



Can pass an entire array as an
argument
Assign values from on array to another
Copy data from one array to another
Array copy


System.arraycopy(sourceArray,
sourcePosition, destinationArray,
destinationPostion, count);
System.arraycopy(y, 0, x, 0, y.length);


Copies y to x but remain separate arrays
System.arraycopy(y, 0, x, 2, 3);

Copies y starting at 0 for next 3 positions
to x starting at position 2
Given that you have 2 arrays


private int[] x = new int[5];
private int[] y = new int[5];
Array Assignment

x = y;




Makes x and y occupy the same storage
space!
Very different than other assignment
statements.
They are now identical
If you change elements of one it changes
the other. (same storage space)
Why??

When you declare an array



int[] x = new int[5];
This allocates 5 storage locations x[0]
through x[4];
Additionally java allocates an additional
storage location x which contains the
address of the start of the array
Why?
x
X[0] X[1] X[2] X[3] X[4]
0
0
0
0
0
Why?
X[0] X[1] X[2] X[3] X[4]
x
0
0
0
0
0
0
0
y = x;
y
Old array y
0
0
0
Example 5.16 Page 294

5.16



Accepts in 2 arrays
Returns true is they are equal
Middle of page

Calls the method
Example 5.7 page 295 - 296



Adds 2 arrays
Accepts in 2 integer arrays
Returns an array which is the sum of
the respective elements in the arrays
sent
Section 5.4 Searching and
Sorting an Array

Two common things that are done with
an array are:



Searching
Sorting
When we search an array you compare
each value to a target, which is the
value you are seeking
PseudoCode
For each array element
If the current element contains the target
return the index of the current element
If none found return -1
Implementation


To test each element of the array we
would use a for loop.
The arrays length attribute can be used
for the upper limit (< length)
Search code
public static int search(int[] x, int target) {
for (int i = 0; i < x.length; i++)
if (x[i] == target)
return i;
//index of target
// All elements tested without success.
return -1;
}
Sorting array





Selection sort is a simple sorting
algorithm
It is not a very efficient algorithm
Finds smallest element in the array and
switches it with element in position 0
Finds next smallest element and
switches it with position 1
And so on…..
Pseudocode

For each index, fill, in the array up to
but excluding, the last index


Find the smallest element in the subarray
starting at scores[fill]
If the smallest element is not at index fill


Exchange the smallest element with the one at
index fill
See code trace page 300
Switching values

If you want to change to values x, y
need a third storage location



temp = x;
x = y;
y = temp;
Sort program

Look at sorting code on page 301



Method selectSort
Method findPosMin
Look at selection sort running at

http://www.cs.hope.edu/~alganim/animato
r/Animator.html
Median Value


Easy to find median in sorted Array
Simply one in the middle
public static int findMedian(int x[]) {
// Create a copy of array x.
int[] copyX = new int[x.length];
System.arraycopy(x, 0, copyX, 0, x.length);
selectSort(copyX); // Sort array copyX
if (x.length % 2 == 1)
return copyX[x.length / 2];
else
return (copyX[(x.length / 2) – 1] +
copyX[x.length/2]) / 2;
Arrays of Objects 7.5
Arrays can be declared of any type in
Java.
 When you create an array of objects
you actually have an array of null
references to objects.
Employee[] employees new Employee[5]
 Allocates storage for 5 references to an
employee object, you must initialize it.

Examples Page 304 - 305

Example shows creating an array of
references to 5 strings.


Page 304 shows creating array and then
setting values.
Page 305 this declares the array and
initializes it at the same time.
Array of string as argument



You can pass array of strings to
methods.
We have been using the format all
along.
public static void main(String[] args);

Passes command line parameters into the
program as string arguments
Code looks like this
public static void main(String[] args) {
if (args.length > 0)
for(int i = args.length - 1; i >=0; i--)
System.out.println(args[i]);
else
System.out.println("No command
line args - no fun!");
}
Case study Payroll problem


Uses company class to include array of
employee objects from section 4.4
New company needs to include 2 new
data items


Array of employees
Total Gross pay
Case study Payroll problem
pages 312 - 314

Implementation


Notice readPayrollData, simply uses a for
loop to instantiate the objects and call
method to prompt user for data.
computePayRoll uses a for loop to total the
pay of all employees

Could this, Should this have been a part of
readAllEmpData??
Case study Payroll problem

Implementation

I have a problem with the design of this.


It revolves around the data field payroll
And the method computePayroll


Especially being public
Any ideas what I don’t like about this?
Case Study Phone Directory

Study the Phone Directory Case study


Work to understand this!
Come with questions for next time.
Multidimensional Arrays
section 5.6



How many can we have?
Two dimensional are the most common
arrays.
These allow more complex structures
than just the linear nature of single
dimensional arrays.
Multidimensional Arrays

The rules for element types of
multidimensional arrays are the same
for single dimensional arrays



Must be the same type
Can be simple or objects
Most commonly used to represent a
table of elements
Declaring 2 dimensional arrays



char [] [] ticTacToe = new char[3][3];
This is a 2d array with 3 rows and 3
columns.
ticTacToe [1] [2]
Array
name
Row
index
Column
index
Initializing a two-dimensional
array


double [] [] matrix = {{5.0, 4.5, 3.0},
{-16.0, -5.9, 0.0}};
Creates an 2 X 3 array
Col 0
Col 1
Col 2
Row 0
5.0
4.5
3.0
Row 1
-16.0
-5.9
0.0
Nested loops for processing 2d
arrays.



You need to decide what order you
intend on accessing the array.
If in row order, then the row index in
used in the outer loop.
If in column order then the column
index is in the outer loop.
Nested loops for processing 2d
arrays.
Pseudocode:
for each row r in the array
for each column c in the array
process the element with indices [r] [c]

Code to process
int intArray [] [] = new int [3] [3];
for (int row = 0; row < intArray.length,
row++)
for (int col = 0; col <
intArray[row].length, col++)
process each array element
intArray[row] [col]
Arrays with different row
lengths

Since each row of a 2d array is it’s own
1d array the length of all row need not
be equal
Arrays > 2d

Why?




Each row is a player and each column is
how many hits they had in each game.
2d array represents a team with each
column a different player
3d represents all the teams in the league
4d represents various seasons for the
league
Section 7.7 Vectors




Vectors are a class within java.
They allow for much of the flexibility
that you will learn to implement in CS2
Must import java.util.*;
Only works with objects not primitive
types
Vector attributes


Allows structure to grow and shrink as
needed
Allows you to:




Add elements
Retrieve elements
Insert elements
Remove elements
Example 5.14 Page 329






Uses vector to store a collection of
employees
Vector employees = new Vector();
employees.addElement(employeeA);
employees.addElement(employeeB);
Puts employeeA at index 0
Puts employeeB at index 1
Accessing elements



anEmployee =
(Employee)employees.elementAt(1);
Assigns to an Employee the second
element in array
elementAt returns a type object so you
must type cast it to the appropriate
type (Employee)
Other methods

setElementAt


insertElementAt


Allows you to insert an element anywhere in the
vector
removeElementAt


Allows you to change an element in the vector
Allows you to delete any element in the vector
See table 5.3 page 332
Review re-do of phone book


On pages 334 – 336 is a re-do of the
Phone Book app you looked at before.
Study and compare this to the previous
example and come prepare to ask any
questions next time
Wrapper classes Section 5.8



Vectors can only work on objects not
primitive data types
A Wrapper class encapsulates a
primitive type and allows it to function
as an object.
Contains methods for converting back
and forth.
Wrapper class methods

Constructor takes primitive type and
create object of that type class


new Double(3.14159)
Holds real number 3.14159 in type Double
object
Wrapper class methods

Constructor to decode string into
objects initial value


Double w = new Double(“3.14159”);
Stores 3.14159 in object of type Double
that is called w
Wrapper class methods

toString method creates string version


typeValue gives primitive type value


w.toString() creates “3.14159”
w.DoubleValue() gives 3.14159
equals compares objects of same type

x.equals(y) is true if the wrap the same
value
Vectors and Wrappers

You need to know what vectors are




Characteristics
Capabilities
Uses
You need to know what Wrapper
classes are


Capabilities
Uses
Section 5.9 Arrays and
ArrayList collection classes

Arrays class

provides a set of static methods to process
arrays





fill()
sort()
binarySearch()
equals()
We will write our own for some of these
ArrayList

Provides and indexed collection





behave like a vector
has greater performance
See methods page 343
See Phone book re-write using ArrayList
Pages 343 - 346
Common programming errors

Most common error is index going
outside the bounds of the array



May want to display index to be sure that it
is processing properly.
Index type must be integer
Must declare array and create an
instance or it.

If not get null pointer error
Common programming errors

Vectors



Do not remove more data than is in the
vector
Be sure to type cast objects as you remove
them
To store primitives in vector must use
wrapper class