Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 1 Unit-5: Array Content A)ObjectivesObjectives B)Why are Arrays neededWhy are Arrays needed C)Creating & Using ArraysCreating & Using Arrays D)Manipulating Arrays with LoopsManipulating Arrays with Loops E)SearchingSearching F)Creating & using Arrays of ObjectsCreating & using Arrays of Objects G)Manipulating Arrays with ObjectsManipulating Arrays with Objects H)Manipulating Arrays with MethodsManipulating Arrays with Methods I)Appendix : More on QUEUEAppendix : More on QUEUE

2 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 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!

4 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 error if (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); } Variablejanfebmaraprmayjunjulaugsepoctnovdec Value31283130313031 30313031 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

5 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) ]

6 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

7 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 2194 Array Variable The content is the reference of the array object Array object Array 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 ;

8 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 Suggestion type 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 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 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 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 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 000000000000 Figure 5.5An array object of 12 elements with initial values

13 13 Initial value Elements of new array object are implicitly initialized Element TypeElement Initial Value byte0 (byte) short0 (short) char0 (char) int0 long0L float0.0 double0.0 booleanfalse all non-primitive typesnull p-10

14 14 More examples String[] stuNames = { Peter, Paul, Mary }; int [ ] fontSize = { 9, 11, 13, 15, 17 }; String [ ][ ] fontDesc = { // a 2-dimension array { TimesRoman, bold }, // 1 st element is an array { Courier, italic }, // 2 nd element is an array { Tahoma, normal } // 3 rd element is an array };

15 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 00000000000 Figure 5.6The interpretation of the expression days[0] days [0];

16 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 array int sum = 0; for ( int i=0; i < tmaScores.length; i++ ) { sum += tmaScore[i]; }

17 17 Stack & Queue Queue ( self test 5.1 ) Not covered in this unit But more sample queue structures in AppendixAppendix 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 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

19 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 20 10 Fig 5.8 Pushing a no. 20 to a stack 10 Fig 5.7 Current stack contents 10 Fig 5.9 Popping a no. from a stack 20 Fig 5.10 Popping another no. 10

20 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 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( ) ); } IntegerStack storage : int [ ] top : int push ( number : int) pop ( ) : int p-16

21 21 More testings // 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( ) ); } } 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 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 stack s1.push(10); s1.push(20); //pop no. from stack & print to screen 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 23 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); 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 24 A shorter version public 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++; > */ } 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

25 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 2 nd implementation ( IntegerStack2 ) 3 rd 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 26 Values of the variables after executing the statement Statement Equivalent statements ij j = ++i; i = i+1; j = i; 66 j = i++; j = i; i = i+1; 65 j = --i; i = i-1; j = i; 44 j = i--; j = i; i = i-1; 45 Table 5.3 Comparing different increment & decrement operators based on an initial value of i = 5 p-27

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 28 60 50 40 30 20 10 The current stack 6 storage [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] length top 0 0 0 0 0 0 0 (1) create a new array 7 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] length [ 6 ] 0 60 50 40 30 20 10 (2) copy stack contents 7 newArray [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] length [ 6 ] newArray 70 60 50 40 30 20 10 (3) 2 variables referring same object 7 newArray [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] length [ 6 ] storage 0 60 50 40 30 20 10 7 newArray [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] length [ 6 ] storage (4) save input data

29 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 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 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 32 Binary search If the items in the collection are sorted ie. in a particular order ( sorting will be covered in Unit-6 ) we dont 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 1 st half or in 2 nd 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 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)thenupdate lower bound by middle point 3.4)elseupdate upper bound by middle point 4)end loop 5)see whether the element left match target or not

34 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; else lowerBound =middle+1; } return target == numbers [ lowerBound ] ; }

35 35 Is 84 contained in the array ? Subscript[0][1][2][3][4][5][6][7] Value123435676849397 Step 1LMU Step 2LMU Step 3LMU Step 4LU

36 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

37 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"; 2 1 0 3 number [ 0 ] [ 1 ] [ 2 ] length 3 greetings [ 0 ] [ 1 ] [ 2 ] length :String value="Good evening" :String value="Good afternoon " :String value="Good morning " p-70 primitive Non-primitive

38 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]; } 2 counters [ 0 ] [ 1 ] length :TicketCounter reading = 456 :TicketCounter reading = 123 temp 2 [ 0 ] [ 1 ] length

39 39 :TicketCounter reading = 456 :TicketCounter reading = 123 temp 2 [ 0 ] [ 1 ] length 2 counters [ 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 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 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 ]

42 I) Appendix : More on QUEUE Out Syllabus

43 43 123 1234 original " 4 " joined 234 " 1 " left Single Queue

44 44 Before ABCD 123 AB1CD 23 priority queue normal queue After moving 1 to the end of the last priority ones B1CD 23 After A left the queue Priority Queue

45 45 1234 4 joined Q1 A Q2 XY Q3 234 A1 XY 1 moved 234 1 XYA A moved 234 1 YA X left Multiple Queues


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

Similar presentations


Ads by Google