L11-1D-Arrays.ppt

Download Report

Transcript L11-1D-Arrays.ppt

King Fahd University of Petroleum & Minerals
College of Computer Science & Engineering
Information & Computer Science Department
ICS102
Lecture 11 : Arrays
July 17, 2016
Arrays

An array is an ordered list of values
Entire array has
A single name
scores
Each value has
A numeric index
[0]
79
[1]
[2]
[3]
62
98
57

An array of size N is indexed from zero to N-1

This array holds 4 values that are indexed from 0 to 3
Processing Array Elements


Access individual elements of an array using:
 the name of the array
 a number (index or subscript) that tells which of the
element of the array
What value is stored in scores[2]?
scores
[0]
79
[1]
[2]
[3]
62
98
57
Arrays

For example, an array element can be assigned a value,
printed, or used in a calculation:
scores[2] = 87;
scores[first] = scores[first] + 2;
Avg = (scores[0] + scores[1])/2;
System.out.println (“Max = " + scores[3]);
Arrays

The values held in an array are called array elements

Array elements are of the same type

The element type can be a primitive type or an object
reference.


Therefore, we can create an array of integers, or an array
of characters, or an array of String objects, etc.
In Java, the array itself is an object

Therefore the name of the array is a object reference
variable, and the array itself must be instantiated
Declaring an Array

Defining an array
Type [] name

Where:
•This declares the handle only
•Initialized to null
•Stores an address when arrays are created

Type specifies the kind of values the array stores

the brackets [ ] indicate this is an array

name is the handle to access the array
Declaring an Array

The scores array could be declared as follows:
double [] scores = new double [4];

The above statement will:

allocate block of memory to hold 4 doubles

initialize block with zeros

create a handle or a pointer or a reference called scores

store address of the block in scores
scores
Handle
[0]
[1]
[2]
0.0
0.0
0.0
Block
[3]
0.0
Syntax

Forms
ElementType [] arrayName;
ElementType [] arrayName = new ElementType [size];
ElementType [] arrayName = array-literal;

Where:

ElementType is any type

arrayName is the handle for the array

array-literal is a list of literals enclosed in curly braces {
}
Declaring Arrays

Some examples of array declarations:
float[] prices = new float[500];
boolean[] flags;
flags = new boolean[20];
char[] codes = new char[1750];
Bounds Checking

Once an array is created, it has a fixed size

An index used in an array reference must specify a valid element

That is, the index value must be in bounds (0 to N-1)


The Java interpreter throws an ArrayIndexOutOfBoundsException
if an array index is out of bounds
This is called automatic bounds checking
Bounds Checking


For example, if the array scores can hold 100 values, it can be
indexed using only the numbers 0 to 99
If scores has the value 100, then the following reference will
cause an exception to be thrown:
System.out.println (scores[count]);

Often for loop is used to process array. It’s common to introduce
off-by-one errors when using arrays
problem
for (int index=0; index <= 100; index++)
scores[index] = index*50 + epsilon;
Bounds Checking


Each array object has a public constant called length that
stores the size of the array
It is referenced using the array name:
scores.length

Note that length holds the number of elements, not the
largest index
Initializer Lists

An initializer list can be used to instantiate and initialize an array in
one step

The values are delimited by braces and separated by commas

Examples:
int[] scores = {98, 76, 54, 83, 87, 65, 99, 66};
char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};
Initializer Lists: Example 1

Used when exact size and initial values of an array are known
in advance
int [] scores = {98, 76, 54, 83}
Visualize the results of the above command
scores
[0]
[1]
[2]
[3]
98
76
54
83
Initializer Lists: Example 2

Consider the following 4 student names
String [] STUDENTS = { “Aref", “Ali“, “Emad”, "Sami"};

Note results:
STUDENTS
[0]
Aref
[1]
Ali
[2]
Emad
[3]
Sami
Array elements are handles for String values
Initializer Lists



Note that when an initializer list is used:

the new operator is not used

no size value is specified
The size of the array is determined by the number of items in
the initializer list
An initializer list can only be used only in the array declaration
The Assignment Operation
Java provides a few operations to use with arrays, including assignment

Consider:
int [] alist = { 1, 12, 15, 7};
int [] blist;
blist = alist;

Recall that alist and blist are handles



alist contains an address of where the numbers are
blist now contains that same address
blist does not have a copy of alist
Array Cloning

To actually create another array with its own values, Java
provides the .clone() method
int [] alist = {1, 12, 15, 7};
int [] blist;
blist = alist.clone();

Now there are two separate lists of numbers, one with handle
alist, the other with handle blist
Array Cloning with Reference Types

Recall previous declaration:
STUDENTS
[0]
Aref

[1]
Ali
[2]
Emad
[3]
Sami
Consider:
Sometimes called a
"shallow copy"
operation
String[] s_list = STUDENTS.clone():

This will create another list of handles, also pointing to the names
Array Cloning with Reference Types

We can write our own "deep copy"
String [] original = {“Aref”,“Ali”, “Emad”, “Sami”};
String [] result = new String(original.length);
for (i = 0; i < original.length; i++)
result[i] = original[i].clone();
Array Equality

Java has an equals() method for classes
if (a1.equals(a2)) …


If a1 and a2 are arrays, the equals() method just looks at
the addresses the handles point to
They could be pointing to different addresses but the contents
of the array still be equal

It is the contents that we really wish to compare
Array Equality

We must write our own method to compare the arrays


they both must have the same length
then use a for( ) loop to compare element by element for
equality
Boolean areEqual
= true;
As soon
as one pair of elements is found
if (list1.length != list2.length)
equal, the arrays are not equal
areEqual =not
false;
else {
for (int i = 0; i < list1.length; i++)
if (list1[i] != list2[i]) areEqual = false;
}
if(areEqual) System.out.println(“They are equal”);
else System.out.println(“They are NOT equal”);
Array exercises


Write an application that inputs 10 numbers, each
between 10 and 100. As each number is read,
display it only if it is not a duplicate of a number
already read.
Given an array of integers, write a java code that
allows to check if the array is “palindromic”. A
palindromic array is a symmetric one:

For example the arrays 1 6 4 6 1 and 258852 are both
palindromic, but the array 3753 is not.
Array exercises

Write a program that reads a sequence of 10 integers
into an array and then computes the alternating sum of
all elements in the array.

For example if the array is : 1 4 9 16 9 7 4 9 11
then it computes : 1 – 4 + 9 – 16 + 9 – 7 + 4 – 9 + 11 = -2
The end
Important to do at home :
- read section 6.1 (pages 372-379)