42
Introduction to arrays

Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

  • View
    229

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Introduction to arrays

Page 2: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Array

• Homogeneous collection of components stored in adjacent memory locations– All elements share same data type– Entire collection identified with single name– Individual elements accessible via indexindex or

subscriptsubscript indicating the element’s position within the collection

• Used to store a relatively large quantity of values of a particular type

Page 3: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Array Basics

• In Java, an array is an indexed collection of data values of the same type.

• Arrays are useful for sorting and manipulating a collection of values.

Page 4: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Example

• Suppose you had to store 20 distinct whole-number values; you now have 2 choices:– Declare 20 distinct int variables, giving each a

unique name– Declare a single int array with the capacity to

hold 20 elements

• Which is preferable? What if the problem involved 200 numbers? 2000? 2,000,000?

Page 5: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Array declaration

• The syntax for array declaration is:data type [ ] identifier;– “data type” is any built-in, library or user-

defined data type (int, double, char, String, etc.)

– “identifier” is a valid Java identifier– Java supports a variation of this syntax, which

is closer to C/C++ syntax:data type identifier[ ];

Page 6: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Array Basics

• In Java, an array is a reference data type.

• We use the new operator to allocate the memory to store the values in an array.

rainfall = new double [12];

//creates an array of size 12.

Page 7: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Array Basics

• An array has a public constant length for the size of an array.

for (i=0; i<rainfall.length; i++){

...

}

• This approach is particularly useful when the size of an array may change, or is not known in advance.

Page 8: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Array Basics

• Do not confuse the length value of an array and the length method of a String object.

• The length is a method for a String object, so we use the syntax for calling a method.

String str = “This is a string”;

int size = str.length();

Page 9: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Array Basics

• An array, on the other hand, is a reference data type, not an object. Therefore, we do not use a method call.

int size = rainfall.length;

Page 10: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Combining declaration & construction

int [] diceCounter = new int[13] ;

char [] upperAlpha = new char[26];

double [] temps = new double[100];

Page 11: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Accessing individual array values

• An element is accessed via its index or subscript; the first element has subscript 0, the second has subscript 1, the third has subscript 2, and so forth up to the last element, which has subscript size-1

• The notation for accessing an element via its subscript is:arrayName[subscript] where – “arrayName” is the array’s identifier– “subscript” is a number between 0 and size-1

Page 12: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Examples

diceValue[12] = 0;

System.out.print(“” + upperAlpha[0]);

temps[7] *= 0.5;• Note: although these examples use literal

values, a subscript can be any integral expression

• It is up to the programmer to ensure that the subscript value is within the bounds of the array – failure to do so will result in a syntax error

Page 13: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

13

What values are assigned?float [] temps = float[ 5 ] ; // allocates memory for array

int m ;

for (m = 0; m < 5; m++)

{

temps[ m ] = 100.0 + m 0.2 ;

}

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

? ? ? ? ?

Page 14: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

14

Now what values are printed?float [] temps = float[ 5 ] ; // allocates memory for arrayint m ;

. . . . .for (m = 4; m >= 0; m-- ){ System.out.println(“” + temps[ m ]) ;}

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

100.0 100.2 100.4 100.6 100.8

Page 15: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

15

Variable Subscripts

float [] temps = new float[ 5 ] ;//allocates memory for arrayint m = 3 ; . . . . . .

What is temps[ m + 1] ?

What is temps[ m ] + 1 ?

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

100.0 100.2 100.4 100.6 100.8

Page 16: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Filling an array with initial values

char [] upperAlpha = new char [26];

for (char c = ‘A’; c <= ‘Z’; c++)upperAlpha[c – ‘A’] = c;

Trace:c c – ‘A’ value stored‘A’ 0 ‘A’‘B’ 1 ‘B’‘C’ 2 ‘C’ . . .‘Z’ 25 ‘Z’‘[‘ 26

Page 17: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Initializing at declaration

char [] lowerAlpha = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’};

List all values in a block of code, terminating with a semicolon:

Compiler automatically sizes array to hold the specified data; array will remain this size, even if different data assigned:

for (int x = 0; x < 10; x++)lowerAlpha[x]=‘!’

Page 18: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Array Basics

• Using constants to declare the array sizes does not always lead to efficient use of space.

• Declaration of arrays with constants is called fixed-size array declaration.

• Fixed-size array declaration may pose two problems:– Not enough capacity for the task at hand.– Wasted space.

Page 19: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Array Basics• In Java, we are not limited to fixed-size array declaration.

• The following code prompts the user for the size of an array and declares an array of designated size:

int size;

int[] number;

size= Integer.parseInt(JOptionPane.showInputDialog(null,

“Size of an array:”));

number = new int[size];

Page 20: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Array Basics

• Any valid integer arithmetic expression is allowed for specifying the size of an array:

size = Integer.parseInt(

JOptionPane.showInputDialog(null,””));

number = new int[size*size + 2* size + 5];

Page 21: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Arrays of Objects

• Arrays are not limited to primitive data types.

• We will use the Person class to illustrate this concept.

• An array of objects is declared and created just as an array of primitive data types is.

Person[] person;

person = new Person[20];

Page 22: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Arrays of Objects

• An array of Person objects after the array is created.

Page 23: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Arrays of Objects

• Array elements are initially null.

• Since each array element is an object, each must also be created.

person[0] = new Person( );

Page 24: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Arrays of Objects

• The person array with one Person object added to it.

Page 25: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Arrays of Objects

• To assign data values to this object, we can execute

person[0].setName (“Ms. Latte”);person[0].setAge (20);person[0].setGender (‘F’);

• The syntax here is the one used to call an object’s method; we are using an indexed expression to refer to the object instead of a simple variable.

Page 26: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Arrays of Objects

• The following program illustrates various aspects of array processing:– Creating a new Person array.– Creating a new Person object and assigning values to

it.– Finding the average age of the persons in the array.– Finding the youngest and oldest persons in the array.– Finding a particular person in the array.

Page 27: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Sample Program (part 1)

import javax.swing.*;

public class ProcessPersonArray {

public static void main (String[ ] args) {

Person[ ] person; //declare the person array person = new Person[5]; //and then create it

//----------- Create person Array ------------//

String name, inpStr; int age; char gender;

Page 28: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Sample program (part 2)for (int i = 0; i < person.length; i++) { // read in data values name = JOptionPane.showInputDialog(null, "Enter name:"); age = Integer.parseInt(JOptionPane.showInputDialog(null,

"Enter age:")); inpStr =JOptionPane.showInputDialog(null, "Enter gender:"); gender = inpStr.charAt(0); // create a new Person and assign values person[i] = new Person( ); person[i].setName ( name ); person[i].setAge ( age ); person[i].setGender( gender );}

Page 29: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Sample program (part 3)

//------ Compute Average Age --------------// float sum = 0, averageAge; for (int i = 0; i < person.length; i++) { sum += person[i].getAge(); } averageAge = sum / (float) person.length;

System.out.println("Average age: " + averageAge); System.out.println("\n");

Page 30: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Sample program (part 4)//-- Find the youngest and oldest person ------////-- Approach No. 3: Using person reference ---//

Person youngest, //points to the youngest person oldest; //points to the oldest person

youngest = oldest = person[0];

for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) { // found a younger person youngest = person[i]; } else if (person[i].getAge() > oldest.getAge() ) { // found an older person oldest = person[i]; }}System.out.println("Oldest : " + oldest.getName() + " is " + oldest.getAge() + "

years old.");

Page 31: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Sample program (part 5)

System.out.println("Youngest: " + youngest.getName() + " is " + youngest.getAge() + " years old.");

//----- Search for a particular person ------// String searchName = JOptionPane.showInputDialog(

null, "Name to search:");

int i = 0;

while ( i < person.length && !person[i].getName().equals( searchName ) ) { //still more persons to search

i++; }

Page 32: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Sample program (part 6)

if (i == person.length) //not found - unsuccessful search {

System.out.println( searchName + " was not in the array" );}

else / /found - successful search { System.out.println("Found " + searchName + " at position " + i);

}

}

}

Page 33: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Arrays of Objects

• Deleting objects from an array requires us to search for the object to be removed.

• When the object is located, there are two ways to delete the object.

Page 34: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Arrays of Objects

• The first approach is to set the array element to null.

• Because each array element is a reference to an object, setting the element to null accomplishes this task easily.

Page 35: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Deleting an object from an array• Approach 1 deletion: Setting a

reference to null. The array length is 4.

Page 36: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Deleting an object from an array

• Any index position may be set to null, but this approach creates “holes” in the array.

• The second approach to deleting an object will order the elements so the real references occur at the beginning and the null references at the end.

Page 37: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Deleting an object from an array: method 2

• Packing the elements so the real references occur at the beginning and the null references occur at the end.

Page 38: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Deleting an object from an array

• We must fill the holes. There are two possible approaches:– If an object at position J is removed (i.e., set to null),

then elements from position J+1 up to the last non-null reference are shifted one position lower. Finally, the last non-null reference is set to null.

– Replace the removed element by the last element in the array.

Page 39: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Deleting an object from an array• Approach 2 deletion: Replace the

removed element with the last element in the array. The array length is 4.

Page 40: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Deleting an object from an array

• Note that assigning null to an array element will not erase the object.

• This operation does initiate a chain reaction that will eventually erase the object from memory.

Page 41: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Arrays of Objects

• A single object may have multiple references pointing to it:

Person p1, p2;

p1 = new Person( );

p2 = p1;

Page 42: Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection

Arrays of Objects

• When an object has no references pointing to it, the system will erase the object and make the memory space available again.

• Erasing an object is called deallocation of memory.

• The process of deallocating memory is called garbage collection. Garbage collection is automatically performed in Java.