Documente Academic
Documente Profesional
Documente Cultură
Introduction to arrays
Background
Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional Java provides arrays and the collection classes The Vector class is an example of a collection class Consider arrays first
Example
Definitions char[] c; int[] value = new int[10]; Causes Array object variable c is un-initialized Array object variable value references a new ten element list of integers Each of the integers is default initialized to 0
c value 0 0 0 0 0
4
An array example
int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt();
v 0 1
v[0]
0
v[1]
0 8
v[2]
0 6
v[3]
0 3
v[4]
0
v[5]
0
v[6]
0 5
v[7]
12 0
v[8]
0
v[9]
5
Brackets Name of Type of list values in indicate array variable being list defined
Basic terminology
List is composed of elements Elements in a list have a common name Example: a[3] = 5; The common name is a The list as a whole is referenced through the common name List elements are of the same type the base type Elements of a list are referenced by subscripting (indexing) the common name
9
10
11
Review of arrays
Creating an array: int[] foo = new int[10]; Accessing an array: foo[3] = 7; System.out.print (foo[1]); Creating an array: String[] bar = new String[10]; Accessing an array: bar[3] = qux; System.out.println (bar[1]);
12
Consider
Segment int[] b = new int[100]; b[-1] = 0; b[100] = 0; Causes Array variable to reference a new list of 100 integers Each element is initialized to 0 Two exceptions to be thrown -1 is not a valid index too small 100 is not a valid index too large IndexOutOfBoundsException
13
Consider
Point[] p = new Point[3]; p[0] = new Point(0, 0); p[1] = new Point(1, 1); p[2] = new Point(2, 2); p[0].setX(1); p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0]; vertex p[2] = vertex;
p[0] p[1] null p[2] null
null
Point: (4, 4)
Point: (1, 2) 1)
Point: (2, 2)
14
Explicit initialization
Syntax
id references an array of n elements. id[0] has value exp0, id[1] has value exp1, and so on.
ElementType []
id = {
Explicit initialization
Example String[] puppy = { pika, mila, arlo, nikki }; int[] unit = { 1 }; Equivalent to String[] puppy = new String[4]; puppy[0] = pika"; puppy[1] = mila"; puppy[2] = arlo"; puppy[3] = nikki"; int[] unit = new int[1]; unit[0] = 1;
16
Array members
Member length Size of the array for (int i = 0; i < puppy.length; ++i) { System.out.println(puppy[i]); } Note that length is a field, not a method! I.e., it is not puppy.length()
17
18
Array members
Member clone() Produces a shallow copy Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1] = new Point(4, 30); u[0] u[1]
u
Point: (0, 0)
Point: (1, 1)
v
v[0] v[1]
Array members
Member clone() Produces a shallow copy Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1].setX(10); u[0] u[1]
u
Point: (0, 0)
v
20
v[0]
v[1]
21
Point: (0, 0)
Point: (2, 1)
Point: (2, 2)
w[0]
w[1]
w[2]
Point: (0, 0)
Point: (2, 1)
Point: (2, 2)
22
23
Todays demotivators
25
4. 5.
tg re at
Th is
el l
el l!
no
I m
It s
el l.
i rl y
ry
y.
ot
Fa
Ve
ka
ot
at a
ll .
I m
Very well! This stuff is easy! Fairly well with a little review, Ill be good Okay. Its not great, but its not horrible, either Not well. Im kinda confused Not at all. Im soooooo lost.
,b u. ..
t ..
st uf
ki n
so oo
it h
da
oo . ..
.. .
fi
c. ..
l it
26
ArrayTools
27
ArrayTools.java
We want to create a series of general utility methods to be used for arrays We will put these into an ArrayTools class
28
ArrayTools.java outline
public class ArrayTools { // class constant private static final int MAX_LIST_SIZE = 1000; // sequentialSearch(): examine unsorted list for key public static int sequentialSearch(int[] data, int key) { ... // putList (): prints list to screen public static void putList(int[] data) { ... // getList(): extract and return up to MAX_LIST_SIZE values public static int[] getList() { ... // reverse(): reverses the order of the element values public static void reverse(int[] list) { ... // binarySearch(): examine sorted list for a key public static int binarySearch(char[] data, char key) { ... }
29
30
31
32
ArrayDemo.java
public class ArrayDemo { // main(): application entry point public static void main(String[] args) { System.out.println (""); System.out.println ("Enter list of integers:"); int[] numbers = ArrayTools.getList (); System.out.println (""); System.out.println ("Your list"); ArrayTools.putList (numbers); ArrayTools.reverse System.out.println System.out.println ArrayTools.putList System.out.println } }
33
ArrayTools demo
ArrayDemo.java
35
4. 5.
tg re at
Th is
el l
el l!
no
I m
It s
el l.
i rl y
ry
y.
ot
Fa
Ve
ka
ot
at a
ll .
I m
Very well! This stuff is easy! Fairly well with a little review, Ill be good Okay. Its not great, but its not horrible, either Not well. Im kinda confused Not at all. Im soooooo lost.
,b u. ..
t ..
st uf
ki n
so oo
it h
da
oo . ..
.. .
fi
c. ..
l it
36
commentator: http://www.cenqua.com/commentator/
37
38
Program Demo
MainParameters.java
40
41
data key i
4 5 0 1 2
if (i != data.length) { System.out.println(key + " is the " + i + "-th element"); } else { System.out.println(key + " is not in the list");42 }
43
82
11
29
85
11
29
91
Consider int[] score = { 6, 9, 82, 11, 29, 85, 11, 28, 91 }; int i1 = sequentialSearch(score, 11); 44 int i2 = sequentialSearch(score, 30);
4. 5.
tg re at
Th is
el l
el l!
no
I m
It s
el l.
i rl y
ry
y.
ot
Fa
Ve
ka
ot
at a
ll .
I m
Very well! This stuff is easy! Fairly well with a little review, Ill be good Okay. Its not great, but its not horrible, either Not well. Im kinda confused Not at all. Im soooooo lost.
,b u. ..
t ..
st uf
ki n
so oo
it h
da
oo . ..
.. .
fi
c. ..
l it
45
d/?ml_video=84023
46
9
1
82
2
11
3
29
4
85
5
9
1
82
2
11
3
29
4
85
5
4. 5.
tg re at
Th is
el l
el l!
no
I m
It s
el l.
i rl y
ry
y.
ot
Fa
Ve
ka
ot
at a
ll .
I m
Very well! This stuff is easy! Fairly well with a little review, Ill be good Okay. Its not great, but its not horrible, either Not well. Im kinda confused Not at all. Im soooooo lost.
,b u. ..
t ..
st uf
ki n
so oo
it h
da
oo . ..
.. .
fi
c. ..
l it
49
Sorting
50
Sorting
Problem Arranging elements so that they are ordered according to some desired scheme Standard is non-decreasing order Why don't we say increasing order? Major tasks Comparisons of elements Updates or element movement
51
Selection sorting
Algorithm basis On iteration i, a selection sorting method: Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example iteration 0 Swaps smallest element with v[0] This results in smallest element being in the correct place for a sorted result
0 1 2 3 4 5 6 7 8 9
Q' 'E'
'W'
E' 'Q'
'R'
'T'
'Y'
'U'
'I'
'O'
'P'
52
Selection sorting
Algorithm basis On iteration i, a selection sorting method: Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example iteration 1 Swaps second smallest element with v[1] This results in second smallest element being in the correct place for a sorted result
0 1 2 3 4 5 6 7 8 9
'E'
'W' 'I'
'Q'
'R'
'T'
'Y'
'U'
'I' 'W'
'O'
'P'
53
Selection sorting
Algorithm basis On iteration i, a selection sorting method: Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example iteration 2 Swaps third smallest element with v[2] This results in third smallest element being in the correct place for a sorted result
0 1 2 3 4 5 6 7 8 9
'E'
'I'
'Q' O'
'R'
'T'
'Y'
'U'
'W'
'O' Q'
'P'
54
Selection sorting
Algorithm basis On iteration i, a selection sorting method: Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example iteration 3 Swaps fourth smallest element with v[3] This results in fourth smallest element being in the correct place for a sorted result
0 1 2 3 4 5 6 7 8 9
'E'
'I'
O'
'R' P'
'T'
'Y'
'U'
'W'
Q'
'P' R'
55
Selection sorting
Algorithm basis On iteration i, a selection sorting method: Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example iteration 4 Swaps fifth smallest element with v[4] This results in fifth smallest element being in the correct place for a sorted result
0 1 2 3 4 5 6 7 8 9
'E'
'I'
O'
P'
'T' Q'
'Y'
'U'
'W'
Q' T'
R'
56
Iteration i
// find the location of the ith smallest element int spot = i; for (int j = i+1; j < v.length; ++j) { if (v[j] < v[spot]) // is spot ok? // update spot with index of smaller element spot = j; } // spot is now correct, swap elements v[spot] and v[i]
58
4. 5.
tg re at
Th is
el l
el l!
no
I m
It s
el l.
i rl y
ry
y.
ot
Fa
Ve
ka
ot
at a
ll .
I m
Very well! This stuff is easy! Fairly well with a little review, Ill be good Okay. Its not great, but its not horrible, either Not well. Im kinda confused Not at all. Im soooooo lost.
,b u. ..
t ..
st uf
ki n
so oo
it h
da
oo . ..
.. .
fi
c. ..
l it
59
60
Binary search
61
Binary search
Given a list, find a specific element in the list List MUST be sorted! Each time it iterates through, it cuts the search space in half A binary search is MUCH faster than a sequential search
62
0: " + ArrayTools.binarySearch(numbers, 0)); 1: " + ArrayTools.binarySearch(numbers, 1)); 4: " + ArrayTools.binarySearch(numbers, 4)); 5: " + ArrayTools.binarySearch(numbers, 5)); 6: " + ArrayTools.binarySearch(numbers, 6)); 10: " + ArrayTools.binarySearch(numbers, 10)); 11: " + ArrayTools.binarySearch(numbers, 11));
BSDemo.java
64
Binary search
public static int binarySearch (int[] data, int key) { int i = 0; // left endpoint of search interval int j = data.length-1; // right endpoint of search interval while ( i < j ) { int m = (i+j)/2; if ( key > data[m] ) { i = m+1; } else { j = m; } } if ( key == data[i] ) { return i; } else { return -1; } 65 }
key
14 6
returns: a6 14 a7 16 a8 18 a9 20
a0 data 2
a1 4
a2 6
a3 8
a4 10
a5 12
0 5 6
4 7 6 5
9 7 6
66
Binary search
But what if the element is not in the list?
67
key
15 -1
returns: a6 14 a7 16 a8 18 a9 20
a0 data 2
a1 4
a2 6
a3 8
a4 10
a5 12
0 5 7
4 7 6
9 7
68
4. 5.
tg re at
Th is
el l
el l!
no
I m
It s
el l.
i rl y
ry
y.
ot
Fa
Ve
ka
ot
at a
ll .
I m
Very well! This stuff is easy! Fairly well with a little review, Ill be good Okay. Its not great, but its not horrible, either Not well. Im kinda confused Not at all. Im soooooo lost.
,b u. ..
t ..
st uf
ki n
so oo
it h
da
oo . ..
.. .
fi
c. ..
l it
69
Binary search
A somewhat alternative view of what a binary search does
70
71
72
4. 5.
tg re at
Th is
el l
el l!
no
I m
It s
el l.
i rl y
ry
y.
ot
Fa
Ve
ka
ot
at a
ll .
I m
Very well! This stuff is easy! Fairly well with a little review, Ill be good Okay. Its not great, but its not horrible, either Not well. Im kinda confused Not at all. Im soooooo lost.
,b u. ..
t ..
st uf
ki n
so oo
it h
da
oo . ..
.. .
fi
c. ..
l it
73
Vector class
74
Limitations of arrays
You cant change their size once created This can be a big problem! So we will create a new class that will operate like an array: We can store and get elements by index number It will automatically increase in size as needed And other fancy features
Lets call the class Vector As we are basically writing the java.util.Vector class
75
76
What happens when the array field is full, and we want to add an element? We will need to increase the size of the array So we need a method to do that as well
77
78
79
80
81
82
Safety Awards
safety_Awards_2006.pps
83
84
85
86
Program Demo
VectorUsage.java
87
88
Program Demo
VectorUsage.java
89
90
91
4. 5.
tg re at
Th is
el l
el l!
no
I m
It s
el l.
i rl y
ry
y.
ot
Fa
Ve
ka
ot
at a
ll .
I m
Very well! This stuff is easy! Fairly well with a little review, Ill be good Okay. Its not great, but its not horrible, either Not well. Im kinda confused Not at all. Im soooooo lost.
,b u. ..
t ..
st uf
ki n
so oo
it h
da
oo . ..
.. .
fi
c. ..
l it
92
93
Multi-dimensional arrays
94
Multidimensional arrays
Many problems require information be organized as a twodimensional or multidimensional list Examples Matrices Graphical animation Economic forecast models Map representation Time studies of population change Microprocessor design
95
Example
Segment int[][] m = new int[3][]; m[0] = new int[4]; m[1] = new int[4]; m[2] = new int[4]; Produces
m[0] m[1] m[2]
m[2][0]
m[2][1]
m[2][2]
m[2][3]
0
m[0][0]
0
m[0][1]
0
m[0][2]
0
m[0][3]
0
m[1][0]
0
m[1][1]
0
m[1][2]
0
m[1][3]
96
Example
Alternative int[][] m = new int[3][4];
Produces
m[0] m[1] m[2]
m[2][0] m[2][1] m[2][2] m[2][3]
0
m[0][0]
0
m[0][1]
0
m[0][2]
0
m[0][3]
0
m[1][0]
0
m[1][1]
0
m[1][2]
0
m[1][3]
97
or
0 0 0
Example
Segment for (int c = 0; c < m.length; ++c) { for (int r = 0; r < m[c].length; ++r) { System.out.print("Enter a value: "); m[c][r] = stdin.nextInt(); } }
0 0 0 0 0 0 0 0 0 0 0 0
99
or
0 0
The answer is that it can be either As long as you are consistent with your column/row 100 placement
101
Example
Segment String[][] s[0] = new s[1] = new s[2] = new s[3] = new Produces
s[0]
null
null null
null
null null
null
null null
s[0][0] s[0][1]
null
null
102
s[1][0] s[1][1]
or
103
Fractals
104
Fractal zooming
http://www.fractalartcontests.com/2000/e
n/entry-004-7.htm
105
Explicit Initialization
Segment int c[][] = {{1, 2}, {3, 4}, {5, 6}, {7, 8, 9}}; Produces
c[0] c[1] c[2] c[3]
c[2][0] c[2][1]
2 3 4
c[0][0] c[0][1]
c[1][0] c[1][1]
106
Matrices
A two-dimensional array is sometimes known as a matrix because it resembles that mathematical concept A matrix a with m rows and n columns is represented mathematically in the following manner
a1 , 1 a 1, 2 a 1, n a2 , 1 a 2, 2 a 2, n am , 1 a m, 2 a m, n
107
Matrix addition
Definition C = A + B
cij = aij + bij cij is sum of the elements in the same row and column of
A and B
108
Matrix addition
public static double[][] add(double[][] a, double[][] b) { // determine number of rows in solution int m = a.length; // determine number of columns in solution int n = a[0].length; // create the array to hold the sum double[][] c = new double[m][n]; // compute the matrix sum row by row for (int i = 0; i < m; ++i) { // produce the current row for (int j = 0; j < n; ++j) { c[i][j] = a[i][j] + b[i][j]; } } return c; }
109
Homework 10
You will be creating a Map class The Map class contains a 2-D array In each spot will be a Location object (from a previous HW) Lab 11 is (was?) going to be a MapPrinter class Will print out the 2-D Map via text
110
4. 5.
tg re at
Th is
el l
el l!
no
I m
It s
el l.
i rl y
ry
y.
ot
Fa
Ve
ka
ot
at a
ll .
I m
Very well! This stuff is easy! Fairly well with a little review, Ill be good Okay. Its not great, but its not horrible, either Not well. Im kinda confused Not at all. Im soooooo lost.
,b u. ..
t ..
st uf
ki n
so oo
it h
da
oo . ..
.. .
fi
c. ..
l it
111
Driving in Bolivia
DrivingInBolivia.pps
112
Wrapper classes
113
114
115
116
Auto-boxing
Java 1.5 will automatically wrap a primitive value into its wrapper class when needed And automatically unwrap a wrapper object into the primitive value So Java translates the previous code into the following: int x = 5; vector.add (new Integer(x)); // int y = ((Integer)vector.get(0)).intValue(); This is called autoboxing And auto-unboxing (unauto-boxing?) This does not work in Java 1.4 or before
118
More on auto-boxing
Consider the following code: Double d = 7.5; Double e = 6.5; Double f = d + e; System.println (f); This is doing a lot of auto-boxing (and auto-unboxing): Double d = new Double(7.5); Double e = new Double(6.5); Double f = newDouble(d.doubleValue() + e.doubleValue()); System.println (f);
119
4. 5.
tg re at
Th is
el l
el l!
no
I m
It s
el l.
i rl y
ry
y.
ot
Fa
Ve
ka
ot
at a
ll .
I m
Very well! This stuff is easy! Fairly well with a little review, Ill be good Okay. Its not great, but its not horrible, either Not well. Im kinda confused Not at all. Im soooooo lost.
,b u. ..
t ..
st uf
ki n
so oo
it h
da
oo . ..
.. .
fi
c. ..
l it
120
121
122