array

advertisement
Introduction to arrays
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 index or
subscript indicating the element’s position
within the collection
• Used to store a relatively large quantity of
values of a particular type
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.
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?
Array declaration
• The syntax for array declaration is:
data type [ ] identifier;
– “data type” is any built-in, library or userdefined 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[ ];
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.
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.
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();
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;
Combining declaration &
construction
int [] diceCounter = new int[13] ;
char [] upperAlpha = new char[26];
double [] temps = new double[100];
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
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
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 ;
}
7000
7004
7008
7012
7016
?
?
?
?
?
temps[0]
temps[1]
temps[2]
temps[3]
temps[4]
13
Now what values are printed?
float [] temps = float[ 5 ] ; // allocates memory for array
int m ;
.....
for (m = 4; m >= 0; m-- )
{
System.out.println(“” + temps[ m ]) ;
}
7000
100.0
temps[0]
7004
7008
7012
7016
100.2
100.4
100.6
100.8
temps[1]
temps[2]
temps[3]
temps[4]
14
Variable Subscripts
float [] temps = new float[ 5 ] ;//allocates memory for array
int m = 3 ;
......
What is temps[ m + 1] ?
What is temps[ m ] + 1 ?
7000
100.0
temps[0]
7004
7008
7012
7016
100.2
100.4
100.6
100.8
temps[1]
temps[2]
temps[3]
temps[4]
15
Filling an array with initial values
char [] upperAlpha = new char [26];
for (char c = ‘A’; c <= ‘Z’; c++)
upperAlpha[c – ‘A’] = c;
Trace:
c
‘A’
‘B’
‘C’
...
‘Z’
‘[‘
c – ‘A’
0
1
2
25
26
value stored
‘A’
‘B’
‘C’
‘Z’
Initializing at declaration
List all values in a block of code, terminating with a
semicolon:
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’};
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]=‘!’
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.
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];
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];
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];
Arrays of Objects
• An array of Person objects after the array
is created.
Arrays of Objects
• Array elements are initially null.
• Since each array element is an object,
each must also be created.
person[0] = new Person( );
Arrays of Objects
• The person array with one Person object
added to it.
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.
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.
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;
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 );
}
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");
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.");
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++;
}
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);
}
}
}
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.
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.
Deleting an object from an array
• Approach 1 deletion: Setting a
reference to null. The array length
is 4.
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.
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.
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 nonnull 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.
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.
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.
Arrays of Objects
• A single object may have multiple
references pointing to it:
Person p1, p2;
p1 = new Person( );
p2 = p1;
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.
Download