Download Document

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Unit-5: Array
Content
A)
B)
C)
D)
E)
F)
G)
H)
I)
Objectives
Why are Arrays needed
Creating & Using Arrays
Manipulating Arrays with Loops
Searching
Creating & using Arrays of Objects
Manipulating Arrays with Objects
Manipulating Arrays with Methods
Appendix : More on QUEUE
1
A) Objectives
1. Describe why arrays are needed.
2. Apply simple arrays of primitive types in Java programs.
3. Apply simple arrays of non-primitive types in Java
programs.
4. Apply searching algorithms on arrays.
B) Why are arrays needed ?
p-3
 What is an array ?
 a collection of data values of the same data type
 size cannot be changed once created
 implemented as an object in Java
 Data to be processed in problems are of the same type
2
eg-1
 in banking system, there could be more than a million
saving accounts (which are of the same type).
 If a different variable is declared to store the
information of a customer, it is difficult to manage and
process the information when the number of customers
is large.
 We may end up with a large number of variables
 adaSavAC, benSavAC, johnSavAC,
 each with a different name referring to a different savings
account object
 Think about the case that if we need to print information out of a
million data items, we need to write a program containing a
million print statements!
3
 eg-2 Given 12 Variables storing 12 Values
Variable jan feb mar apr may
Value
31
28
31
30
31
jun
jul
aug sep oct nov dec
30
31
31
30
31
30
31
 to verifying whether it is a valid day in the month
boolean valid = false;
if (month == 1)
if (month == 2)
if (month == 3)
if (month == 4)
if (month == 5)
if (month == 6)
if (month == 7)
if (month == 8)
if (month == 9)
if (month == 10)
if (month == 11)
if (month == 12)
{ valid
{ valid
{ valid
{ valid
{ valid
{ valid
{ valid
{ valid
{ valid
{ valid
{ valid
{ valid
day is a variable to be
tested for validity
= (day <= jan); }
= (day <= feb); }
It is tedious &
= (day <= mar); }
error prone to use
= (day <= apr); }
12 variables to
= (day <= may); }
represent the data
= (day <= jun); }
= (day <= jun); } // vulnerable for error
= (day <= aug); }
= (day <= sep); }
= (day <= oct); }
= (day <= nov); }
= (day <= dec); }
4
Eg-3
 Using array, which can store a collection of data items with a
single variable; days ( in this example, rather than 12 variables )
An Array contaning all
valid number of days
of each month
The curly bracket pair, { } is
used to assign values to the
12 elements of an array
// define a variable days &
// an array object containing no. of days each month of a year
int[ ] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// declares the variable valid &
// test whether the value of the variable day is a valid day in the month
boolean valid = ( day <= days [ month – 1 ] ) ;
day is a variable
to be tested for
validity
range of array of n elements
is [ 0 .. (n-1) ]
" <= " is a comparison operator
5
C) Creating and using arrays
p-5
Use of arrays :
1. An array is implemented as an object in Java
2. Data stored in an array are called : the elements of the array , or
 simply array elements
3. All elements of an array must be of the same type
 Array enables you to
 access a collection of data/objects of the same
type with a single variable
 a collection of data items is also called a data structure
 There are 2 data structures : 1) object and 2) array 6
Steps to use an array in Java:
1. declare an array reference variable
2. create the array object
3. access array elements using a variable (with a subscript)
arrayVar
2
1
9
4
Array Variable
The content is the
reference of the
array object
int arrayVar[] ;
arrayVar = new int[4];
Array object
Array element
Figure 5.2 A typical scenario of using an array (p-6)
arrayVar[0] = 2 ;
arrayVar[1] = 1 ;
arrayVar[2] = 9 ;
arrayVar[3] = 4 ;
7
Declaring array variables
p-7
 a pair of square brackets denotes an array type
type [] variable-name;
type variable-name [];
// King's Suggestion
 Both are valid; it is only a matter of personal style
 array type can be primitive or non-primitive
int [] tmaScores;
Student [] group10;
// primitive
// non-primitive
 more eg.
String [] args;
int [ ] a, b;
int a [ ], b;
// as in main ( )
// both a & b of type int [ ]
// only a of type int [ ]
// b is simply int
8
 When an array variable is declared, no array object is
immediately available
 It is just like you have declared an object but not yet
created it
 an array is an object in Java
 must use keyword new to create it explicitly.
9
Creating Array Objects
 To create an array object, you have to tell how many
elements the array needs to store.
 Creating an array is similar to creating an object, using
the new keyword.
new type [ number_of_elements ]
 eg.
int [ ] days;
// 1) declare a variable days
days = new int [ 12 ] ; // 2) create array of 12 elements
 alternatively
int [ ] days = new int [ 12 ] ;
10
int [ ] days;
// 1) declare a variable days
days = new int [ 12 ] ;
// 2) create array of 12 int elements
days
Such an object is the
array object referred by
the variable days
Figure 5.4 An array variable is initialized with an array object
 declaration of an array variable (line-1) does not need the
array size ; just the array element type
 but create an array object needs both type & size
11
 so, a variable of type array of int can refer to
 array objects with any array size
 provided that the element type is int.
 eg. the variable days can refer : to an array object of 12 elements of type int or
 to an array object of 10 elements of type int
 Array will be implicitly initialized :
days
0
0
Figure 5.5
0
0
0
0
0
0
0
0
0
0
An array object of 12 elements with initial values
12
Initial value
p-10
 Elements of new array object are implicitly initialized
Element Type
Element Initial Value
byte
short
char
int
long
float
double
boolean
all non-primitive types
0 (byte)
0 (short)
0 (char)
0
0L
0.0
0.0
false
null
13
More examples
String[] stuNames = { “Peter”, “Paul”, “Mary” };
int [ ] fontSize = { 9, 11, 13, 15, 17 };
String [ ][ ] fontDesc = {
{ “TimesRoman”, “bold” },
{ “Courier”, “italic” },
{ “Tahoma”, “normal” }
};
// a 2-dimension array
// 1st element is an array
// 2nd element is an array
// 3rd element is an array
14
Accessing elements in arrays
 accessing array element, we use a subscript (or index),
which can be a simple integer or any expression that
results in an integer
 eg.
days [0];
days
0
0
0
Figure 5.6
0
0
0
0
0
0
0
0
0
The interpretation of the expression days[0]
15
 A subscript starts with zero
 If the array has n elements,
 the subscript is ranged between 0 and n-1
 The pair of square brackets [ ] is an operator in Java and
it takes precedence over other operators
int [] tmaScores = new int [4];
double average = ( tmaScores[0] + tmaScores[1]
+ tmaScores[2] + tmaScores[3] ) / 4;
int sum = 0; for ( int i=0; i < 4; i++ ) { sum += tmaScore[i]; }
int size = tmaScores.length; // size of array
int sum = 0; for ( int i=0; i < tmaScores.length; i++ )
{ sum += tmaScore[i]; }
 It is a runtime error if we access array elements out of
the above range.
 please refer p-21 for sample exception messages
16
Stack & Queue
p-30
 Queue ( self test 5.1 )
 Not covered in this unit
 But more sample queue structures in Appendix
 a queue has a front and a rear.
 New entry is always put at the rear and next entry is
always got from the front.
 Hence a queue is a first-in-first-out (FIFO)
structure.
 A queue has a front pointer and rear pointer
 There are two behaviors: enqueue & dequeue.
 Unlike stack class, there is no direct queue class in
Java API.
17
Stack
p-12
 A stack is like a pile of dishes. The last dish you place on
top of the pile would be the first one you take.
 This is a Last-In-First-Out (LIFO) operation
 A stack has a stack-top pointer
 Basically, there are 2 behaviours, namely push and pop.
 push places a number on top of other numbers
 pop return the topmost number and remove it
 There is a stack class in Java API: java.util.Stack
 further info
http://java.sun.com/j2se/1.4.1/docs/api/java/util/Stack.html
18
Stack operations
10
 a stack currently has a number 10
Fig 5.7 Current
stack contents
 after performed push with data 20,
 the stack object places 20 on top of 10
 after performed pop ,
 the number 20 is returned & removed
 after another pop ,
 the number 10 is returned & removed
 resulting in an empty stack
20
10
Fig 5.8 Pushing a
no. 20 to a stack
20
10
Fig 5.9 Popping a
no. from a stack
10
Fig 5.10 Popping
another no.
19
Example IntegerStack1
IntegerStack
storage : int [ ]
top : int
public class TestIntegerStack1 { // page-18
public static void main (String args[]) {
//create a Stack instance
IntegerStack1 s1= new IntegerStack1();
push ( number : int)
pop ( ) : int
public class IntegerStack1 {
//attribute
private int [] storage = new int[6];
private int top = 0;
//behaviour
public void push (int number) {
storage [ top ] = number;
top++;
}
public int pop () {
top--;
return storage [ top ];
}
}
p-16
//push integer to the stack
s1.push(10);
s1.push(20);
//pop no. from stack & print to screen
System.out.println(s1.pop( ) );
System.out.println(s1.pop( ) );
}
}
20
More testings
p-19
// test with number of push > array size
public class TestIntegerStack2 {
public static void main (String args[]) {
// create a Stack instance
IntegerStack1 s1=new IntegerStack1( );
// push integer to the stack
s1.push(10); s1.push(20); s1.push(30);
s1.push(40); s1.push(50); s1.push(60);
s1.push(70); // test on our of subscript error
// pop no. from stack & print to screen
for (int j=0; j<6; j++) { System.out.println(s1.pop( ) ); }
}
Error message : invalid array subscript
}
of 6, viz. lager then ( 6-1 )
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at IntegerStack1.push(IntegerStack1.java:19)
at TestIntegerStack2.main(TestIntegerStack2.java:18)
21
// test with 2 push but 3 pop
p-20
public class TestStack3 {
public static void main (String args[]) {
//create a Stack instance
IntegerStack1 s1= new IntegerStack1();
//push integer to the stack
s1.push(10);
s1.push(20);
}
//pop no. from stack & print to screen
System.out.println(s1.pop( ) );
System.out.println(s1.pop( ) );
System.out.println(s1.pop( ) );
}
Error message :
invalid array subscript of -1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at IntegerStack1.pop(IntegerStack1.java:32)
at TestIntegerStack3.main(TestIntegerStack3.java:18)
22
Verifying subscript before access
public class IntegerStack2 {
private int[] storage = new int[6];
private int top;
public void push(int number) {
System.out.println(
"DEBUG: Push " + number);
p-22
public int pop() {
System.out.println(
"DEBUG: Pop");
int result = -1;
if (top > 0) {
top--;
result = storage[top];
}
else {
System.out.println(
"The stack is empty");
}
return result;
if (top < 6) {
storage[top] = number;
top++;
}
else {
System.out.println(
"The stack is full");
}
}
}
}
23
A shorter version
p-22
public class IntegerStack3 {
private int[] storage = new int[6];
private int top;
public void push(int number) {
System.out.println(
"DEBUG: Push " + number);
public int pop() {
System.out.println(
"DEBUG: Pop");
int result = -1;
if (top > 0) {
/* >> top--; << deleted >> */
result = storage[--top];
}
else {
System.out.println(
"The stack is empty");
}
return result;
if (top < 6) {
storage[top++] = number;
/* >> top++; << deleted >> */
}
else {
System.out.println(
"The stack is full");
}
}
}
}
24
Pre- & Post- operations
 If increment & decrement are used alone, the placing
of the operators does not matter; so i++ ; = ++i ;
 if it is placed after a variable, a post-increment operator
or post-decrement operator. eg storage [ top++ ] = number;
 the value of the variable is used before the value is
increased or decreased by one.
where
use
2nd implementation
3rd implementation
push
(post)
storage[top] = number;
top++;
storage[top++] = number;
pop
(pre)
top--;
result = storage[top];
result = storage[--top];
( IntegerStack2 )
( IntegerStack3 )
Table 5.2 The comparison of the implementations IntegerStack2 and IntegerStack3
25
Table 5.3
p-27
Comparing different increment & decrement operators
based on an initial value of i = 5
Values of the variables after
executing the statement
Equivalent
statements
Statement
j = ++i;
j = i++;
j = --i;
j = i--;
i
j
j
i
i
j
j
i
=
=
=
=
=
=
=
=
i+1;
i;
i;
i+1;
i-1;
i;
i;
i-1;
i
j
6
6
6
5
4
4
4
5
26
D) Manipulating arrays with loops
p-39
 Since an array object could not be resized, the only way to use a
new array object with larger size is to
 create a new array object with larger size &
 copy the contents from the original one to the new one
 Now re-writing a push method to expand the array size
public void push (int number) {
System.out.println("DEBUG: Push " + number);
if (top == storage.length) {
int[] newArray = new int[storage.length +1]; // 1)create a new array
for (int i=0; i < storage.length ; i++) {
// 2) copy all old elements
newArray[i] = storage[i];
// last element is empty
}
storage = newArray;
// 3) 2 variables referring to the same Array
}
storage[top++] = number;
// 4) store number as the last Array element
}
27
storage
top
60
50
40
30
20
10
[5]
[4]
[3]
[2]
[1]
[0]
6
length
newArray
The current stack
newArray
0
60
50
40
30
20
10
[6]
[5]
[4]
[3]
[2]
[1]
[0]
7
length
(2) copy stack contents
0
0
0
0
0
0
0
[6]
[5]
[4]
[3]
[2]
[1]
[0]
7
length
(1) create a new array
newArray
storage
0
60
50
40
30
20
10
[6]
[5]
[4]
[3]
[2]
[1]
[0]
7
length
(3) 2 variables referring
same object
newArray
storage
70
60
50
40
30
20
10
[6]
[5]
[4]
[3]
[2]
[1]
[0]
7
length
(4) save input data
28
E) Searching
p-54
 You have a collection of data of the same type using
arrays but it is often necessary to determine :
 if a data item exists in a collection, ( 有 / 無 ) or
 if some data fulfill particular conditions ( 有幾多 )
 The simplest way is to check each array element one by
one (sequentially) whether the desired data is found
 It is like reading the job advertisements one by one to
see if you fit their requirements
29
Linear search (Sequential Search)
 No need to assume any ordering of items in the
collection.
 The idea is to check each item one by one, starting from
the first one. When the first item matching the criteria is
found, the process can stop or go on to find the next
matching item
 this method is simple & works well for small arrays
 As each element is searched one by one,
 the time required to search for a target
 increases with number of element in the array object
 not an efficient way for a huge amount of elements
 Please refer to the LinearSearcher.java on page-57
30
public class LinearSearcher {
private int numbers[] = new int[1000];
private int total;
public void storeNumber (int number){
if (total < numbers.length) {
numbers[total++] = number;
} else {
System.out.println(
"Too many numbers");
}
}
public boolean contains (int target) {
boolean found = false;
for (int i=0; i < total; i++) {
if (numbers[i]==target){
found=true;
}
}
return found;
}
// counting number of occurrence
public int count (int target) {
int result = 0;
for (int i=0; i < total; i++) {
if (numbers[i] == target) {
result++;
}
}
return result;
}
}
31
Binary search
 If the items in the collection are sorted
 ie. in a particular order ( sorting will be covered in Unit-6 )
 we don’t need to check each item one by one
 The idea is to repeatedly divid the scope into 2 halves
 check if the target exist in 1st half or in 2nd half
 the process is stopped until there is one element left
 then conclude if the target is found or not.
 Also refer to BinarySearcher.java on page-65
 Please refer to a static method binarySearch( ) for
class Arrays in :
http://java.sun.com/j2se/1.4.1/docs/api/java/util/Arrays.html
32
Algorithm
1) sort the searching scope if not be sorted beforehand
2) set the upper bound and lower bound
3) loop until lower bound larger than upper bound
3.1)
find out the middle point
3.2)
if target larger than middle point
3.3)
then update lower bound by middle point
3.4)
else update upper bound by middle point
4) end loop
5) see whether the element left match target or not
33
public boolean contains (int target) {
int lowerBound =0;
int upperBound = total – 1;
while (lowerBound < upperBound) {
int middle = ( lowerBound
+ upperBound) /2;
if (target <= numbers[middle])
upperBound=middle;
else
lowerBound =middle+1;
}
return target == numbers [ lowerBound ] ;
}
34
Is 84 contained in the array ?
Subscript
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
Value
1
23
43
56
76
84
93
97
Step 1
L
M
U
Step 2
L
M
Step 3
LM
U
Step 4
U
LU
35
F) Creating and using array of objects
p-68
 Recalling that the steps to create and use an array of
primitive types are:
 declare the array ( eg. int [] number; )
 create the array ( eg. number = new int [100]; )
 access the array elements ( eg. number [10] )
 Now, if the array is of non-primitive types (ie. array of
objects), we have to create each array element before
accessing them. For example,
Student[] group10 = new Student[40];
group10[0] = new Student( );
group10[0].name = “Peter”;
36
Array objects of primitive & non-primitive types
int[] numbers = new int[3];
numbers[0] = 0;
numbers[1] = 1;
numbers[2] = 2;
number
2
1
0
3
p-70
String[] greetings = new String[3];
greetings[0] = "Good morning";
greetings[1] = "Good afternoon";
greetings[2] = "Good evening";
[2]
[1]
[0]
length
[2]
primitive
[1]
[0]
greetings
3
length
:String
value="Good evening"
:String
value="Good afternoon "
:String
value="Good morning "
Non-primitive
37
G) Manipulating arrays with objects
 Two TicketCounter
objects are created and are
referred to by the array
object that is referred by
variable counters
 both temp and counters
refer to the two same
TicketCouner objects;
hence these are equal :
 temp[i].increase();
 counters[i].increase();
counters
TicketCounter[ ] counters = new
TicketCounter[2];
counters[0] = new TicketCounter ();
counters[1] = new TicketCounter ();
TicketCounter[] temp = new
TicketCounter [counters.length];
for (int i=0; i < counters.length; i++) {
temp [i] = counters [i];
}
[1]
[0]
2
2
:TicketCounter
reading = 456
length
[1]
[0]
temp
p-83
length
:TicketCounter
reading = 123
38
 If we need another set of TicketCounter objects with the same
reading, then
1. create 2 new TicketCounter objects,
2. set their reading accordingly
for (int i=0; i < counters.length; i++) {
temp[i] = new TicketCounter();
temp[i].setReading ( counters[i].getReading() );
}
counters
[1]
[0]
2
length
[1]
[0]
temp
2
length
:TicketCounter
reading = 456
object 1
:TicketCounter
reading = 123
object 2
:TicketCounter
reading = 456
object 3
:TicketCounter
reading = 123
object 4
39
H) Manipulating arrays with methods
p-85
 The type of the parameter, args, of the main() method is
an array of String
public static void main ( String [ ] args ) { …… }
 [ args ] is actually an array of String objects which
are optionally passed in when the program is executed.
 To execute a program:
java Program Program-parameter-list
 eg.
java TestArgs First Second Third "Fourth Item"
40
java TestArgs First Second Third "Fourth Item"
 the program parameters after the class name TestArgs
are referred by array elements and the array object is
passed to the main ( ) method as shown in Figure 5.72.
:String
value = "Fourth Item"
[3]
[2]
args
[1]
[0]
4
length
:String
value = "Third"
:String
value = "Second"
:String
value = "First"
41
I) Appendix : More on QUEUE
Out Syllabus
Single Queue
1
original
2
3
"4" joined
1
2
3
"1" left
2
3
4

4

43
Priority Queue
 Before

1
2
3
A
B
C
priority queue
normal queue
D
 After moving 1 to the end of the last priority ones
2
3
A
B
1
C
D
 After A left the queue

2
3
B
1
C
D
44
Multiple Queues
Q1
Q2
Q3
1
2
3
A
X
Y
2
3
A
1
X
Y
2
1
3
4
X
Y
A
2
1
3
4
Y
A
4
4
4 joined
1 moved

A moved
X left
45