Lecture8

advertisement
Chapter 9, Arrays
The primitive and reference variables we have discussed so far are “single-valued” in that
each contains a single value, either an exact value or a reference to an object. There is
another category of variables that allows us to associate a single variable name with
multiple values, these are called Arrays. In programs, arrays are used to store SETS of
related values (called elements), that can be manipulated collectively or individually.
Some of the things we might keep in arrays are: the students in a particular class, a set of
numbers that need to be sorted or searched, or a set of points that need to be drawn on a
graph. To create arrays, Java provides us with a “class” Array that permits the storage
and retrieval of multiple values/objects of the same type, through access to a single
variable name.
The syntax to create an array in Java is :
1. type [] identifier;
int[] values;
or
2. type [] identifier = new type[i];
int[] values = new int[4];
In these examples:
 type represents the data type of the “elements” stored in the array. This
“type” can be any primitive or reference (class) type
 identifier represents the variable name of the array variable being created.
int [] intArray;
 creates an array of integers called intArray. At this point it is
uninitialized which means that it has no storage associated with it, and
thus it can not be used to store values. Before an array can be used, we
must allocate storage, by indicating HOW many values will be stored in
the array. We can do this by
intArray = new int[4];
int[] anArray = new int[5];
 creates an integer array called anArray and initializes it so that it can
store a maximum of 5 values.
Conceptually, when an array is allocated, a contiguous (sequential) set of bytes are
allocated in memory to store the values contained in the array. In our previous example,
this would allocate memory sufficient to store 5 integer values:
We can think of each of these memory locations as “slots” into which we can place data.
Like characters in a String, each element has associated with it an “index” number. The
first slot always has the index 0. The indices for an array object are always in the range 0
to #entries -1.
0
1
2
3
4
NOTE: Java initializes the elements of an array when it is created. By default zero is
stored into each element of a numeric array (int or float), false is stored into Boolean
array elements, and null is stored into each element of arrays of objects.
So to begin with our array looks like:
anArray
0
0
0
0
0
0
1
2
3
4
Our array variable anArray contains the address of the first element of the array. To
reference or assign a value to an array entry, we specify the index number of that entry
as:
variableName[i]
for example:
 anArray[0] refers to the first element in the array
 anArray[3] refers to the 4th element of the array
To assign a value to an array element:
 anArray[2] = 56;
anArray
0
0
56
0
0
0
1
2
3
4


x = anArray[2]; would assign the value 56 to the variable x
int x = 1; anArray[x] = 99; stores the value 99 into the second element of the
array.
anArray
0
99
56
0
0
0
1
2
3
4
Array indexes can be specified using:
 integer literals ‘2’
 integer variables
 or expressions that yield an integer value
The only restriction is that the index value generated must be an integer and, must be
within bounds of the array: ie between zero and the number of elements in the array
minus 1. If an index is out of bounds, then the exception will occur during execution.
Specifying array size during execution
We can declare an “array” without specifying how many elements it contains, when this
is done no memory is allocated, until the declaration is complete. We do this because
sometimes the size of an array is not known until the program is actually executing.
Perhaps the program will need to prompt for the number of values to be entered, and then
create the array. This can be easily accomplished via:
int numElements:
int[] list;
System.out.println(“Please enter the maximum number of values that will be input “);
numElements = console.nextInt();
list = new int[numElements];
Specifying default values when an array is declared:
It is also possible to initialize array elements when the array is declared, if initial values
are known.
String[] names = {“Cam”, “Brett”, “Audrey”, “Ian”};
would create a 4 element string array, containing the values:
0
1
2
3
Cam
Brett
Audrey
Ian
names
When the elements of an array are instances of a class each element contains a reference
to the actual object instance. Methods that are appropriate for that instance can be
applied by:
arrayName[index].method( parameters);
ie:
names[0].length() would yield 3
names[2].charAt[1] would yield ‘u’
To create an instance of a class, and assign it to an array element.
names[1] = new String(“Donna”);
Class Array instance variables, and methods
Arrays in Java, are implemented as instances of a special class called Arrays, and class
Arrays provides several useful methods and instance variables that can help us use and
manipulate Arrays in our programs.
length
The instance variable “length” is created for each Array object, and can be accessed to
determine the number of elements in the array. Please note, that this is the number of
elements allocated to the array, which may or may not reflect the actual number of value
stored into the array.
names.length would return the integer value 4
When ever we write loops that access all of the elements in an array, we should always
use the “length” instance variable to determine the number of elements in the array as
part of good software engineering practices, rather than hard coding the number of
elements as an integer literal.
Example 1:
Lets write a program to enter 3 names, and print them out in the reverse order they were
entered; We could code this as:
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String [] names = new String[3];
for (int i=0; i < names.length; i++) {
System.out.println(“please enter a name”);
names[i] = input.next();
}
// to print the names in reverse
for (int i = names.length-1; i >= 0; i--)
System.out.println(names[i]);
}
We could have coded the first loop as:
for (int i = 0; i < 3; i++)
However if the we later wish to modify our program, and change the number of names
from 3 to 5, we have a problem where our program will have to be modified in multiple
places.. ie in both the declaration of names and in the loop. It is conceivable that we could
forget to make the modification in all of the places that the change needs to occur, and
this degrades maintainability. If however we use .length we would only need to modify
the size of our array in the declaration statement. You also need to remember that for
arrays “length” is an instance variable, and for Strings “length” is a method!!!
Methods for class Arrays
Class Arrays provides us with several instance and static methods which we can use to
manipulate the elements of array variables. (Class array is part of package java.util)

static method “fill”: this method can be used to initialize all of the elements in
an array to the same value.
int[] anArray = new int[5];
Arrays.fill(anArray, 99);
anArray
99
99
99
99
99
0
1
2
3
4

Static method “equals” This method compares two arrays (of the same type),
element by element to determine if they contain the same values. To be equal, the
arrays must contain the same number of elements in the same order. If the arrays
are equal, the method returns true, false otherwise. There are several versions of
this method (ie the method is overload) that allow us to compare integer, double,
float, character, and Boolean arrays.
int [] grades1 = {72, 84, 100};
int [] grades2 = { 72, 84, 100};
int [] grades3 = { 84, 72, 100};
int [] grades4 = { 72, 84};
if (Arrays.equals(grades1, grades2))
System.out.println(“grades1 equals grades2”);
else
System.out.println(“grades1 does not equal grades2”);
if (Arrays.equals(grades1, grades3))
System.out.println(“grades1 equals grades3”);
else
System.out.println(“grades1 does not equal grades3”);
if (Arrays.equals(grades1, grades4))
System.out.println(“grades1 equals grades4”);
else
System.out.println(“grades1 does not equal grades4”);
would print:
grades1 equals grades2
grades1 does not equal grades3
grades1 does not equal grades4
Collection based for loops:
Java also provides a very simple method of iterating though all of the elements in an
array, returning the values stored in the elements one at a time. If our task is to
retrieve each entry and do something with it.. this feature will work well: it has the
format:
for (type variable: array_variable)
For example, lets create an array of test scores, and the calculate the sum of the
grades and the average.
int[] grades = { 72, 88, 66, 99, 100};
int sum = 0;
double average = 0.0;
//This loop assigns each value in the grades array to the variable aValue one at a
//time. This is a “foreach” loop
for (int aValue : grades) {
sum += aValue;
}
average = (double)sum/ grades.length;
System.out.println(“The average of the “ + grades.length + “ scores is: “ +
average);
would display:
The average of the 5 scores is: 85.0
Example programs:
1. Write a Java program that declares an array called alpha with 50 elements of
the type double. Initialize the array so that the first 25 components are equal to
the square of the index value (for that component) and the next 25 components
are equal to three times the index value for that component. Output the array so
that 10 elements per line are printed.
public class ex1{
public static void main(String [] args) {
double[] alpha = new double[50];
int count =1;
for (int i = 0; i < alpha.length; i++) {
if (i < (alpha.length/2)) alpha[i] = i*i;
else alpha[i] = i * 3;
}
System.out.println("The elements of the array are: ");
for (int i=0; i <alpha.length; i++){
if (count <=10) {
System.out.print(alpha[i]+ " ");
}
else{
System.out.println();
System.out.print(alpha[i]+ " ");
count = 1;
}
count++;
}
System.out.println();
}
}
This displays:
The elements of the array are:
0.0 1.0 4.0 9.0 16.0 25.0 36.0 49.0 64.0 81.0
100.0 121.0 144.0 169.0 196.0 225.0 256.0 289.0 324.0 361.0
400.0 441.0 484.0 529.0 576.0 75.0 78.0 81.0 84.0 87.0
90.0 93.0 96.0 99.0 102.0 105.0 108.0 111.0 114.0 117.0
120.0 123.0 126.0 129.0 132.0 135.0 138.0 141.0 144.0 147.0
2. Write a java program that prompts the user to input a string and then outputs the
string in uppercase letters (use a character array to store the string).
import java.util.*;
public class hello {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char[] name;
String line;
System.out.println("Please enter a name");
line = input.next();
// We need a way to convert a String into a character array..
// Check out class String… use the instance method
// toCharArray.
name = line.toCharArray();
System.out.println("the original string was: "+line);
// We need to convert each character to upper case.
// Characters in Java are stored internally as an integer code
// Knowing this face means that we can perform arithmetic on characters.
// ‘a’+1 yields ‘b’. Characters are ordered so that
// 0-9 < A-Z < a-z
// for any given lower case letter, it’s corresponding upper case letter
// has an integer representation that is 32 less.
// so ‘a’ – 32 == ‘A’
for (int i=0; i < name.length; i++)
System.out.print((char)(name[i]-32));
System.out.println();
}
}
________________________________________________________________
/home/hayhurst/java- java hello
Please enter a name
abcdefghijklmnopqrstuvwxyz
the original string was: abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Download