Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays An array collects a sequence of values of the same type

Similar presentations


Presentation on theme: "Arrays An array collects a sequence of values of the same type"— Presentation transcript:

1

2 Arrays An array collects a sequence of values of the same type
Sequence of values are called elements The sequence of values are store under a single name. An array can be visualized as a series of boxes, each capable of holding a single value belonging to this type: An array whose elements are arranged in a linear fashion is said to be a one-dimensional array.

3 Declaring 1-D arrays An array declaration contains [ and ] symbols (“square brackets”): int[] a; The elements of an array can be of any type. In particular, array elements can be objects: String[] b; It’s also legal to put the square brackets after the array name: int a[]; String b[];

4 Declaring Arrays Declaring an array variable doesn’t cause Java to allocate any memory for the array’s elements. One way to allocate this memory is to use the new keyword: a = new int[10]; You can declare and reserve memory for array at the same time: int[] a = new int[10]; The value inside the square brackets can be any expression that evaluates to a single int value: int n = 10; int[] a = new int[n];

5 Initializing arrays When an array is created using new, the elements of the array are given default values: Numbers are set to zero. boolean elements are set to false. Array and object elements are set to null. E.g int[] values = new int[10]; values 1 2 3 4 5 6 7 8 9

6 Example

7 Arrays Array elements are indexed by position number
Start index: 0 End index: array length – 1 Each index position uniquely identifies an element. First index is always 0 Last index is always length-1 a 1 2 3 4 5 6 7 8 9 Index values length of a = no. of elements = 10

8 Initializing array element values
Method 1: Initialize array at the time it’s declared specify the initial values when you create the array double[] values ={32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65 }; Do NOT use keyword new You don’t need to specify number of elements. Method 2: use the [] operator double[] values = new double[10]; Specify index of element: values[4] = 35; values[1] = 20; values 1 2 3 4 5 6 7 8 9 32 54 67.5 29 35 80 115 44.5 100 65 values 1 2 3 4 5 6 7 8 9 20 35

9 Example

10 Accessing Array Elements
Individual elements are accessed by an integer index i, using the notation array[i] where array is the array name values[3] An array element can be used like any variable: System.out.println(values[4]); Result = values[2];

11 Syntax 7.1 Arrays

12 Declaring Arrays

13 Programming Question Write a tester program called ArrayDemo. Class should : Declare an int array called values of 5 elements. Assign each element the value of its index. Print all elements along with the index. A sample run is shown: values[0] = 0 values[1] = 1 values[2] = 2 values[3] = 3 values[4] = 4 Print the values variable. What happens? Modify the program so that you have 1000 elements. As previous, each element should store value of it’s index. Try printing value at index= What happens?

14 Answer ArrayDemo.java public class ArrayDemo{
public static void main(String args[]) { final int n = 10; int values[] = new int[n]; for(int i=0; i<n;i++) { values[i] = i; } System.out.printf("values[%d]=%d\n", i, values[i]); System.out.println("values = "+values); System.out.println("values[10]="+values[10]);

15

16 Arrays – Bounds Error A error you just saw is called a bounds error
Bounds error occurs if you supply an invalid array index. Causes your program to terminate with a run-time error. Example: double[] values = new double[10]; values[10] = value; // Error, non-existing index

17 Example

18 Array Length values.length yields the length of the values array.
There are no parentheses following length. When iterating through elements in an already initialized array, we use this: for(int i=0; i<values.length;i++) { values[i] = i; }

19 Example

20 Array References Copying an array reference yields a second reference to the same array. (like objects) When you copy an array variable into another, both variables refer to the same array int[] scores = { 10, 9, 7, 4, 5 }; int[] values = scores; // Copying array reference

21 Array References You can modify the array through either of the variables: scores[3] = 10; System.out.println(values[3]); // Prints 10 int[] scores = { 10, 9, 7, 4, 5 }; int[] values = scores; // Copying array reference

22 Example

23 Using Arrays with Methods
Arrays can occur as method arguments and return values. An array as a method argument public void addScores(int[] values) { for (int i = 0; i < values.length; i++) totalScore = totalScore + values[i]; } To call this method int[] scores = { 10, 9, 7, 10 }; addScores(scores); A method with an array return value public int[] getScores()

24 Partially Filled Arrays
Array length = maximum number of elements in array. Usually, array is partially filled Define an array larger than you will need final int LENGTH = 100; double[] values = new double[LENGTH]; How do you find out how many elements are actually in the array?

25 Partially Filled Arrays
How do you find out how many elements are actually in the array? Use companion variable to keep track of current size: call it currentSize

26 Partially Filled Arrays
A loop to fill the array int currentSize = 0; Scanner in = new Scanner(System.in); while (in.hasNextDouble()) { if (currentSize < values.length) values[currentSize] = in.nextDouble(); currentSize++; } At the end of the loop, currentSize contains the actual number of elements in the array. Note: Stop accepting inputs when currentSize reaches the array length. Scanner sc = new Scanner(System.in); double values = new double[10]; for(int i=0;i<values.length;i++) { values[i] = sc.nextDouble(); } // int currentSize = 0; while(sc.hasNextDouble()) //as long as user enters a number if(currentSize<values.length) values[currentSize++] = sc.nextDouble(); S.o.p("current no. of elements="+currentSize);

27 Partially Filled Arrays

28 Partially Filled Arrays
To process the gathered array elements, use the companion variable, not the array length: for (int i = 0; i < currentSize; i++) { System.out.println(values[i]); } With a partially filled array, you need to remember how many elements are filled.

29 Question Given an array of integers containing the first five prime numbers, int[] primes = { 2, 3, 5, 7, 11 }; what does it contain after executing the following loop? for (int i = 0; i < 2; i++) { primes[4 - i] = primes[i]; } i=0; primes[4-0] = primes[0] = 2 primes[4-1] = primes[1] = 3

30 Answer Given an array of integers containing the first five prime numbers, int[] primes = { 2, 3, 5, 7, 11 }; what does it contain after executing the following loop? for (int i = 0; i < 2; i++) { primes[4 - i] = primes[i]; } i=0; primes[4-0] = primes[0] = 2 primes[4-1] = primes[1] = 3 Answer: 2, 3, 5, 3, 2

31 Programming Question Write a class ArrayDemo2 to do the following:
Define a double array called rainfall with maximum100 elements. Initialize each element by user keyboard input. User can any time denote that he/she is done entering numbers by inputting non-number value. i.e. user is not required to enter values for all 100 elements. Calculate and print average rainfall. A sample run is shown: >Enter rainfall: A > The average rainfall is 38.96

32 Hint: double[] rainfall = new double[100];
Scanner in = new Scanner(System.in); System.out.println("Enter rainfall: "); int currentSize=0; do { //read data to array }while(in.hasNextDouble())//while user enters a double

33 Answer ArrayDemo2.java import java.util.Scanner;
public class ArrayDemo2 { public static void main(String args[]) double[] rainfall = new double[100]; Scanner in = new Scanner(System.in); System.out.println("Enter rainfall: "); int currentSize=0; do if(currentSize < rainfall.length) rainfall[currentSize] = in.nextDouble(); currentSize++; } }while(in.hasNextDouble()); double average = 0.0; double total = 0.0; for(int i=0;i<currentSize;i++) total += rainfall[i]; average = total/currentSize; System.out.printf("Average rainfall=%3.2f", average);

34 The Enhanced for Loop You can use the enhanced for loop to visit all elements of an array. E.g. Totaling the elements in an array with the enhanced for loop double[] values = {10.5, 3.2, 6.7}; double total = 0; for (double element : values) //for each element in array { total = total + element; } The loop body is executed for each element in the array values. Indices are not accessible Element type Element name Array name Try this in ArrayDemo2.java Total calculation

35 ArrayDemo2.java total calculation
for(double e: rainfall) { total += e; }

36 The Enhanced for Loop Enhance for loop: Traditional alternative:
for (double element : values) //for each element in array { total = total + element; } Indices are NOT accessible Traditional alternative: for (int i = 0; i < values.length; i++) double element = values[i]; Indices are accessible

37 The Enhanced for Loop Not suitable for all array algorithms.
Does NOT allow you to modify the contents of an array. E.g. The following loop does NOT fill an array with zeros: for (double element : values) { element = 0; // ERROR: this assignment does not modify // array elements } Use a basic for loop instead: for (int i = 0; i < values.length; i++) values[i] = 0; // OK

38 The Enhanced for Loop Use the enhanced for loop if you do not need the index values in the loop body. The enhanced for loop is a convenient mechanism for traversing all elements in a collection.

39 Syntax 7.2 The Enhanced for Loop

40 Programming Question Given the following array:
int[] a = {2, 78, 6 ,67, 23, 2 , 7 , 8 , 0 , 23} Write ArrayDemo3 class with a method maximum to find and print the maximum of array elements: public static int maximum(int values[]) Class template in next slide

41 Class template import java.util.Scanner; public class ArrayDemo3{
public static void main(String args[]) { int[] a = {2, 78, 6 ,67, 23, 2 , 7 , 8 , 0 , 23}; System.out.println("maximum= "+ maximum(a)); } public static int maximum(int values[]) { //TODO

42 Answer ArrayDemo3.java import java.util.Scanner;
public class ArrayDemo3{ public static void main(String args[]) { int[] a = {2, 78, 6 ,67, 23, 2 , 7 , 8 , 0 , 23}; System.out.println("maximum= "+ maximum(a)); } public static int maximum(int values[]) { int largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest= values[i]; return largest;

43 Question Consider the algorithm to find the largest element in an array. Why don’t we initialize largest and i with zero, like this? double largest = 0; for (int i = 0; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } Original code: double largest = values[0]; for (int i = 1; i < currentSize; i++){ if (values[i] > largest){ largest = values[i]; }

44 Answer If all elements of values are negative, then the result is incorrectly computed as 0.

45 Programming Question Linear Search: Given the following array:
A linear search inspects elements in sequence until a match is found. Given the following array: int[] a = {2, 78, 6 ,67, 23, 2 , 7 , 8 , 0 , 23} Write ArrayDemo4 class with a method search to search for a value and print index of element in array if found. Otherwise print “not found!” Class template in next slide

46 public class ArrayDemo4{
public static void main(String args[]) { int[] a = {2, 78, 6 ,67, 23, 2 , 7 , 8 , 0 , 23}; search(78, a); search(28, a); } public static void search (int searchedValue, int values[]) { //TODO

47 Answer import java.util.Scanner; public class ArrayDemo4{
public static void main(String args[]) { int[] a = {2, 78, 6 ,67, 23, 2 , 7 , 8 , 0 , 23}; search(78, a); search(28, a); } public static void search (int searchedValue, int values[]) { int index = 0; boolean found = false; while (index < values.length && !found) { if (values[index] == searchedValue) { found = true; } else { index++; } if (found) { System.out.println("Found at position: " + index); } else { System.out.println("Not found"); } public static void search (int searchedValue, int values[]) { int index = 0; boolean found = false; while (index < values.length && !found) { if (values[index] == searchedValue) { found = true; break; } else { index++; } } if (found) { System.out.println("Found at position: " + index); } else { System.out.println("Not found"); }

48 Common Array Algorithm: Copying an Array
Copying an array variable yields a second reference to the same array: double[] values = {1, 3, 45, 5, 20} double[] prices = values; To make a true copy of an array, call the Arrays.copyOf method: double[] prices = Arrays.copyOf(values, values.length); Explore javadoc API page for Arrays

49

50 Java.util.Arrays class

51

52 Common Array Algorithm: Copying an Array
Figure 11 Copying an Array Reference versus Copying an Array

53 Common Array Algorithm: Growing an Array
To grow an array that has run out of space, use the Arrays.copyOf method to double the length of an array double[] newValues = Arrays.copyOf(values, 2 * values.length); values = newValues;

54

55 Two-Dimensional Arrays
An arrangement consisting of rows and columns of values Also called a matrix. Example: medal counts of the figure skating competitions at the 2010 Winter Olympics. Figure 13 Figure Skating Medal counts

56 Two-Dimensional Arrays
Use a two-dimensional (2-D)array to store tabular data. When constructing a two-dimensional array, specify how many rows and columns are needed: final int COUNTRIES = 7; //number of rows (dimension 1) final int MEDALS = 3; //number of columns (dimension 2) int[][] counts = new int[COUNTRIES][MEDALS]; 2-d array of 7 rows and 3 columns OR 7 arrays each having 3 elements (array of arrays) rows columns

57 Example

58 Two-Dimensional Arrays
int[][] counts = new int[COUNTRIES][MEDALS]; memory counts Each row is a 1-d array

59 Two-Dimensional Arrays
Method1: You can declare and initialize the array by grouping each row: int[][] counts = { { 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 1, 1, 0 } }; You cannot change the size of a two-dimensional array once it has been declared.

60 Example

61 Two-Dimensional Arrays
Method2: Declare array first: inal int COUNTRIES = 7; final int MEDALS = 3; int[][] counts = new int[COUNTRIES][MEDALS]; Assign values to individual elements: E.g. counts[0][2]=1 [0] [1] [2] row=0 column-2 [0] [1] [2] [3] [4] [5] [6] Ref: Memory handling in Java Java handles its memory in two areas. The heap and the stack. We will start with a short overview of memory in general on a computer. Then the Java heap and stack is explained. 2.1. Native Memory Native memory is the memory which is available to a process, e.g. the Java process. Native memory is controlled by the operating system (OS) and based on physical memory and other physical devices, e.g. disks, flash memory, etc. The processor (CPU) of the computer computes the instructions to execute and stores its computation results into registers. These registers are fast memory elements which stores the result of the CPU. The processor can access the normal memory over the memory bus. A amount of memory a CPU can access is based on the size of the physical address which the CPU uses to identify physical memory. A 16-bit address can access 2^16 (=65.536) memory locations. A 32-bit address can access 2^32 (= ) memory locations. If each memory area consists of 8 bytes then a 16-bit system can access 64KB of memory and the 32-bit system can access 4GB of memory. An operating system (OS) normally uses virtual memory to map the physical memory to memory which each process can see. The OS assigns then memory to each process in a virtual memory space for this process and maps access to this virtual memory to the real physical memory. Current 32-bit systems uses an extension (Physical Address Extension (PAE)) which extends the physical space to 36-bits of the operation system. This allows the OS to access 64GB. The OS uses then virtual memory to allow the individual process 4 GB of memory. Even with PAE enabled a process can not access more than 4 GB of memory. Of course with a 64-bit OS this 4GB limitation does not exist anymore. 2.2. Memory in Java Java manages the memory for use. New objects created and placed in the heap. Once your application have no reference anymore to an object the Java garbage collector is allowed to delete this object and remove the memory so that your application can use this memory again. 2.3. Java Heap In the heap the Java Virtual Machine (JVM) stores all objects created by the Java application, e.g. by using the "new" operator. The Java garbage collector (gc) can logically separate the heap into different areas, so that the gc can faster identify objects which can get removed. The memory for new objects is allocated on the heap at run time. Instance variables live inside the object in which they are declared. 2.4. Java Stack Stack is where the method invocations and the local variables are stored. If a method is called then its stack frame is put onto the top of the call stack. The stack frame holds the state of the method including which line of code is executing and the values of all local variables. The method at the top of the stack is always the current running method for that stack. Threads have their own call stack. 2.5. Escape analysis As stated earlier Java objects are created and stored in the heap. The programming language does not offer the possibility to let the programmer decide if an object should be generated in the stack. But in certain cases it would be desirable to allocate an object on the stack, as the memory allocation on the stack is cheaper than the memory allocation in the heap, deallocation on the stack is free and the stack is efficiently managed by the runtime. The JVM uses therefore internally escape analysis to check if an object is used only with a thread or method. If the JVM identify this it may decide to create the object on the stack, increasing performance of the Java program. 2.6. Memory leaks The garbage collector of the JVM releases Java objects from memory as long as no other object refers to this object. If other objects still hold references to these objects, then the garbage collector of the JVM cannot release them. 3. Garbage Collector The JVM automatically re-collects the memory which is not used any more. The memory for objects which are not referred any more will be automatically released by the garbage collector. To see then the garbage collector starts working add the command line argument "-verbose:gc" to your virtual machine. An in-depth article about the garbage collector can be found here: Tuning Garbage Collection with the 5.0 Java Virtual Machine 4. Memory settings for Java virtual machine The JVM runs with fixed available memory. Once this memory is exceeded you will receive "java.lang.OutOfMemoryError". The JVM tries to make an intelligent choice about the available memory at startup (see Java settings for details) but you can overwrite the default with the following settings. To turn performance you can use certain parameters in the JVM.

62 Example

63 Syntax 7.3 Two-Dimensional Array Declaration

64 Accessing Elements Access by using two index values, array[i][j]
int medalCount = counts[3][1]; For(int row=0; row<values.length; row++) { int[] rowData = values[row]; for(int colum = 0; column<rowData.length;column++) }

65 Example

66 Question Given int[][] rating= new int[3][4];
What is the value of rating.length ? What is the value of rating[0].length ? What is the value of rating[0]? Use DrJava interaction pane to find out!

67 Answer Given int[][] rating= new int[3][4];
What is the value of rating.length ? Answer: 3, the number of rows (first dimension) What is the value of rating[0].length ? Answer: 4, the number of columns (second dimension) What is the value of rating[0]? Answer:{0,0,0,0} Use nested loops to access all elements in a two-dimensional array.

68 2d array = array of arrays

69 Programming Question Write ArrayDemo6 class to declare and initialize the counts array and then print the values in the array in a tabular format. Hint: for printing the row and column headers, define two separate arrays Number of rows: counts.length Number of columns: counts[0].length A sample program run is shown below: Program template in next slide

70 Class Template public class ArrayDemo6{
public static void main(String args[]){ int[][] counts = {{ 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 0, 1, 1 }, { 1, 1, 0 } }; //initialize headers String[] columnHeader = {"Country", "Gold", "Silver", "Bronze"}; String[] rowHeader = {"Canada","China","Germany","Korea","Japan","Russia","United States"}; //print column headers for(int i = 0; i < columnHeader.length; i++)//for each column { System.out.printf("%15s",columnHeader[i]); //print column header } System.out.println(); //TODO: print array in tabular format (Hint: use System.out.printf statements)

71 Answer ArrayDemo6.java public class ArrayDemo6{
public static void main(String args[]){ int[][] counts = {{ 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 0, 1, 1 }, { 1, 1, 0 } }; //iniialize headers String[] columnHeader = {"Country", "Gold", "Silver", "Bronze"}; String[] rowHeader = {"Canada","China","Germany","Korea","Japan","Russia","United States"}; //print column headers for(int i = 0; i < columnHeader.length; i++)//for each column { System.out.printf("%15s",columnHeader[i]); //print column header } System.out.println(); //print array in tabular format for (int i = 0; i < counts.length; i++) //for each row //print row header System.out.printf("%15s",rowHeader[i]); for (int j = 0; j < counts[0].length; j++)//for each element in row i System.out.printf("%15d", counts[i][j]); //print element

72 Homework: Programming Question
Modify ArraysDemo6.java to print a new column with the total number of medals won by each country Hint: This is same as sum of each row A sample run is shown below:

73 Accessing Rows and Columns
Hint To find the number of medals won by a country Find the sum of the elements in a row To find the sum of the ith row compute the sum of counts[i][j], where j ranges from 0 to MEDALS - 1.

74 Answer ArrayDemo6.java public class ArrayDemo7{
public static void main(String args[]){ int[][] counts = {{ 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 },{ 0, 1, 1 }, { 0, 1, 1 }, { 1, 1, 0 } }; //iniialize headers String[] columnHeader = {"Country", "Gold", "Silver", "Bronze","Total"}; String[] rowHeader = {"Canada","China","Germany","Korea","Japan","Russia","United States"}; //print column headers for(int i = 0; i < columnHeader.length; i++)//for each column { System.out.printf("%15s",columnHeader[i]); //print column header } System.out.println(); //print array in tabular format for (int i = 0; i < counts.length; i++) //for each row //print row header System.out.printf("%15s",rowHeader[i]); int total = 0; for (int j = 0; j < counts[0].length; j++)//for each element in row i System.out.printf("%15d", counts[i][j]); //print element total += counts[i][j]; System.out.printf("%15d", total); //print total


Download ppt "Arrays An array collects a sequence of values of the same type"

Similar presentations


Ads by Google