Top Banner
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

1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

Mar 27, 2015

Download

Documents

Molly Bradley
Welcome message from author
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
Page 1: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 2: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 3: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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!

Page 4: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

4

boolean valid = false;if (month == 1) { valid = (day <= jan); }if (month == 2) { valid = (day <= feb); }if (month == 3) { valid = (day <= mar); }if (month == 4) { valid = (day <= apr); }if (month == 5) { valid = (day <= may); }if (month == 6) { valid = (day <= jun); }if (month == 7) { valid = (day <= jun); } // vulnerable for

errorif (month == 8) { valid = (day <= aug); }if (month == 9) { valid = (day <= sep); }if (month == 10) { valid = (day <= oct); }if (month == 11) { valid = (day <= nov); }if (month == 12) { valid = (day <= dec); }

Variable jan feb mar apr may jun jul aug sep oct nov dec

Value 31 28 31 30 31 30 31 31 30 31 30 31

eg-2 Given 12 Variables storing 12 Values

to verifying whether it is a valid day in the month

It is tedious &error prone to use 12 variables to represent the data

day is a variable to be tested for validity

Page 5: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

5

Eg-3

// 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 ] ) ;

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

day is a variable to be tested for validity " <= " is a comparison operator

range of array of n elements is [ 0 .. (n-1) ]

Page 6: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

6

C) Creating and using arrays

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

p-5

Page 7: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

7

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

Array objectArray element

Figure 5.2 A typical scenario of using an array (p-6)

int arrayVar[] ;arrayVar = new int[4];

arrayVar[0] = 2 ;arrayVar[1] = 1 ;arrayVar[2] = 9 ;arrayVar[3] = 4 ;

Page 8: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

8

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

Page 9: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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.

Page 10: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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 ] ;

Page 11: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 12: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 13: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 14: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

};

Page 15: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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];

Page 16: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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]; }

Page 17: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 18: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

further info

http://java.sun.com/j2se/1.4.1/docs/api/java/util/Stack.html

p-12

Page 19: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

19

Stack operations a stack currently has a number 10

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

2010

Fig 5.8 Pushing a no. 20 to a stack

10Fig 5.7 Current stack contents

10Fig 5.9 Popping a no. from a stack

20

Fig 5.10 Popping another no.

10

Page 20: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

20

Example IntegerStack1

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 ];

}}

public class TestIntegerStack1 { // page-18

public static void main (String args[]) {

//create a Stack instanceIntegerStack1 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( ) );

}}

IntegerStack

storage : int [ ]top : int

push ( number : int)pop ( ) : int

p-16

Page 21: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

21

More testings// test with number of push > array sizepublic 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( ) ); }}

}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 )

Page 22: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 23: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 24: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 25: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 26: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 27: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 28: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 29: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 30: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 31: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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; }}

Page 32: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 33: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 34: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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 ] ;

}

Page 35: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 36: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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,

p-68

Page 37: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

37

Array objects of primitive & non-primitive types

int[] numbers = new int[3];

numbers[0] = 0;numbers[1] = 1;numbers[2] = 2;

String[] greetings = new String[3];greetings[0] = "Good morning";greetings[1] = "Good afternoon";greetings[2] = "Good evening";

210

3

number

[ 0 ][ 1 ][ 2 ]

length

3greetings

[ 0 ]

[ 1 ]

[ 2 ]

length

:Stringvalue="Good

evening"

:Stringvalue="Good afternoon "

:Stringvalue="Good morning "

p-70

primitive

Non-primitive

Page 38: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

38

G) Manipulating arrays with objects p-83

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

Page 39: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

Page 40: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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"

Page 41: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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 ]

Page 42: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

I) Appendix : More on QUEUE

Out Syllabus

Page 43: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

43

1 2 3

1 2 3 4

original

"4" joined

2 3 4"1" left

Single Queue

Page 44: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

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

B 1 C D

2 3

After A left the queue

Priority Queue

Page 45: 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating.

45

1 2 3 4 4 joinedQ1

AQ2X YQ3

2 3 4

A 1

X Y

1 moved

2 3 4

1

X Y A A moved

2 3 4

1

Y A X left

Multiple Queues