arrays in java

Download Report

Transcript arrays in java

Collections
behaviour and implementation
of
collections of primitives and objects
Arrays – of primitive types
 arrays are objects
 array variables contain references to arrays
int[] x = new int[5];
x[2] = 550;
// indexing starts at 0
x
0
0
550
0
0
D. Goforth, COSC 3106, fall 2003
2
Arrays – of objects
 arrays of object types
 array variables contain references to
arrays of references
String[] y = new String[5];
y[2] = “Hello”;
y
Hello
D. Goforth, COSC 3106, fall 2003
3
Arrays
accessing individual elements
 find size of array with length variable
int[] x = new int[5];
x[2] = 550;
int number = x.length;//number contains 5
 index range: 0 to length-1
x[0] = 100;
x[4] = -20;
x[5] = 1000;
// ArrayIndexOutOfBoundsException thrown
D. Goforth, COSC 3106, fall 2003
4
Partly filled arrays
 problem with collection of items that
changes in size
eg list of paddleboats for rental
inventory is 10 boats but number
available varies between 0 and 10
use array of integers to store identity
numbers of boats available
D. Goforth, COSC 3106, fall 2003
5
Partly filled arrays
 array length is fixed
 data is always at front of array
 use an integer counter to track how
many data items are in the array
xCount
x
4
701 68 550 -320 0
D. Goforth, COSC 3106, fall 2003
0
0
50 109
0
6
Partly filled arrays
 when new data is added to next
location, count is increased
xCount
4
x
xCount
x
701 68 550 -320 0
0
0
50 109
0
701 68 550 -320 112
0
0
50 109
0
5
D. Goforth, COSC 3106, fall 2003
7
Partly filled arrays
 example – BoatCollection
 inventory collection of boats that are
rented out and returned
 BoatCollection.html
 BoatCollection.java
D. Goforth, COSC 3106, fall 2003
8
Multi-dimensional arrays
 to represent matrices, tables,
calendar months, patch arrays
 e.g., distance chart
Sudbury
Toronto
0
1
Ottawa
2
Sudbury
0
0
400
500
Toronto
1
400
0
600
Ottawa
2
500
600
0
D. Goforth, COSC 3106, fall 2003
9
Multi-dimensional arrays
int[][] m = new int[3][4];
m[2][3] = -60;
0
1
2
3
0
0
0
0
0
1
0
0
0
0
2
0
0
0
-60
D. Goforth, COSC 3106, fall 2003
10
Review of some array operations
 first question: entire array or ‘real’
data subset?
 sum of data
 maximum value
 range of data
 increment every value
 search for value
D. Goforth, COSC 3106, fall 2003
11