1 Unit-5: Array Content A) Objectives B) Why are Arrays needed C) Creating & Using Arrays D) Manipulating Arrays with Loops E) Searching F) Creating & using Arrays of Objects G) Manipulating Arrays with Objects H) Manipulating Arrays with Methods I) Appendix : More on QUEUE
45
Embed
1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
1
Unit-5: Array
Content
A) Objectives
B) Why are Arrays needed
C) Creating & Using Arrays
D) Manipulating Arrays with Loops
E) Searching
F) Creating & using Arrays of Objects
G) Manipulating Arrays with Objects
H) Manipulating Arrays with Methods
I) Appendix : More on QUEUE
2
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 ? 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
p-3
3
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!
Declaring array variables a pair of square brackets denotes an array type
Both are valid; it is only a matter of personal style array type can be primitive or non-primitive
more eg.
type [] variable-name; // King's Suggestiontype variable-name [];
int [] tmaScores; // primitive
Student [] group10; // non-primitive
String [] args; // as in main ( )int [ ] a, b; // both a & b of type int [ ]int a [ ], b; // only a of type int [ ]
// b is simply int
p-7
9
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.
10
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.
eg.
alternatively
new type [ number_of_elements ]
int [ ] days; // 1) declare a variable days
days = new int [ 12 ] ; // 2) create array of 12 elements
int [ ] days = new int [ 12 ] ;
11
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
days Such an object is the array object referred by
the variable days
int [ ] days; // 1) declare a variable days
days = new int [ 12 ] ; // 2) create array of 12 int elements
12
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 0 0 0 0 0 0 0 0 0 0
Figure 5.5 An array object of 12 elements with initial values
13
Initial value Elements of new array object are implicitly initialized
Element Type Element Initial Value
byte 0 (byte)
short 0 (short)
char 0 (char)
int 0
long 0L
float 0.0
double 0.0
boolean false
all non-primitive types null
p-10
14
More examples
String[] stuNames = { “Peter”, “Paul”, “Mary” };
int [ ] fontSize = { 9, 11, 13, 15, 17 };
String [ ][ ] fontDesc = { // a 2-dimension array
{ “TimesRoman”, “bold” }, // 1st element is an array
{ “Courier”, “italic” }, // 2nd element is an array
{ “Tahoma”, “normal” } // 3rd element is an array
};
15
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 0 0 0 0 0 0 0 0 0 0 0
Figure 5.6 The interpretation of the expression days[0]
days [0];
16
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
It is a runtime error if we access array elements out of the above range. please refer p-21 for sample exception messages
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 arrayint sum = 0; for ( int i=0; i < tmaScores.length; i++ )
{ sum += tmaScore[i]; }
17
Stack & Queue 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.
p-30
18
Stack 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
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( ) ); }}
}Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at IntegerStack1.push(IntegerStack1.java:19) at TestIntegerStack2.main(TestIntegerStack2.java:18)
p-19
Error message : invalid array subscript of 6, viz. lager then ( 6-1 )
22
// test with 2 push but 3 pop public class TestStack3 {
public static void main (String args[]) {//create a Stack instance
IntegerStack1 s1= new IntegerStack1();
//push integer to the stacks1.push(10); s1.push(20);
//pop no. from stack & print to screenSystem.out.println(s1.pop( ) );System.out.println(s1.pop( ) );System.out.println(s1.pop( ) );
}}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at IntegerStack1.pop(IntegerStack1.java:32) at TestIntegerStack3.main(TestIntegerStack3.java:18)
p-20
Error message : invalid array subscript of -1
23
Verifying subscript before accesspublic class IntegerStack2 { private int[] storage = new int[6]; private int top; public void push(int number) { System.out.println(
"DEBUG: Push " + number);
if (top < 6) {storage[top] = number;top++;
} else {
System.out.println("The stack is
full"); } }
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; }}
p-22
24
A shorter versionpublic class IntegerStack3 { private int[] storage = new int[6]; private int top; public void push(int number) { System.out.println(
"DEBUG: Push " + number);
if (top < 6) {storage[top++] =
number; /* >> top++; << deleted
>> */ } else {
System.out.println("The stack is full");
} }
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; }}
p-22
25
Pre- & Post- operations If increment & decrement are used alone, the
placing of the operators does not matter; so = if it is placed after a variable, a post-increment operator or
post-decrement operator. eg the value of the variable is used before the value is
increased or decreased by one.
i++ ; ++i ;
storage [ top++ ] = number;
where use
2nd implementation( IntegerStack2 )
3rd implementation( IntegerStack3 )
push(post)
storage[top] = number;
top++;
storage[top++] = number;
pop(pre)
top--;result = storage[top];
result = storage[--top];
Table 5.2 The comparison of the implementations IntegerStack2 and IntegerStack3
26
Values of the variables afterexecuting the statement
StatementEquivalent
statements i j
j = ++i;i = i+1;j = i;
6 6
j = i++;j = i;i = i+1;
6 5
j = --i;i = i-1;j = i;
4 4
j = i--;j = i;i = i-1;
4 5
Table 5.3 Comparing different increment & decrement operatorsbased on an initial value of i = 5
p-27
27
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
}
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
D) Manipulating arrays with loops p-39
28
605040302010
The current stack
6
storage
[ 0 ][ 1 ][ 2 ]
[ 3 ][ 4 ][ 5 ]
length
top 0000000
(1) create a new array
7
[ 0 ][ 1 ][ 2 ]
[ 3 ][ 4 ][ 5 ]
length
[ 6 ]
0605040302010
(2) copy stack contents
7
newArray
[ 0 ][ 1 ][ 2 ]
[ 3 ][ 4 ][ 5 ]
length
[ 6 ]
newArray
70605040302010
(3) 2 variables referring same object
7
newArray
[ 0 ][ 1 ][ 2 ]
[ 3 ][ 4 ][ 5 ]
length
[ 6 ]
storage
0605040302010
7
newArray
[ 0 ][ 1 ][ 2 ]
[ 3 ][ 4 ][ 5 ]
length
[ 6 ]
storage
(4) save input data
29
E) Searching 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
p-54
30
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
31
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; }}
32
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
33
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
34
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;
elselowerBound =middle+1;
}return target == numbers [ lowerBound ] ;
}
35
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 U
Step 3 LM U
Step 4 LU
36
Student[] group10 = new Student[40];group10[0] = new Student( );group10[0].name = “Peter”;
F) Creating and using array of objects 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,
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();
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];}
2counters [ 0 ]
[ 1 ]
length
:TicketCounter reading = 456
:TicketCounter reading = 123
temp2
[ 0 ][ 1 ]
length
39
:TicketCounter reading = 456
:TicketCounter reading = 123
temp2
[ 0 ][ 1 ]
length
2counters [ 0 ]
[ 1 ]
length
:TicketCounter reading = 456
:TicketCounter reading = 123
for (int i=0; i < counters.length; i++) { temp[i] = new TicketCounter(); temp[i].setReading ( counters[i].getReading() );}
If we need another set of TicketCounter objects with the same reading, then 1. create 2 new TicketCounter objects,2. set their reading accordingly
object 4
object 1
object 2
object 3
40
H) Manipulating arrays with methods The type of the parameter, args, of the main() method
is an array of String
[ args ] is actually an array of String objects which are optionally passed in when the program is executed.
To execute a program:
eg.
public static void main ( String [ ] args ) { …… }
p-85
java Program Program-parameter-list
java TestArgs First Second Third "Fourth Item"
41
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 = "Second"
:String
value = "First"
args
4
[ 0 ]
[ 1 ]
length
:String
value = "Fourth Item"
:String
value = "Third"[ 2 ]
[ 3 ]
I) Appendix : More on QUEUE
Out Syllabus
43
1 2 3
1 2 3 4
original
"4" joined
2 3 4"1" left
Single Queue
44
Before
A B C D
1 2 3
A B 1 C D
2 3
priority queue
normal queue
After moving 1 to the end of the last priority ones