Arrays Examples
Arrays Examples
• Array Basics
• Arrays in Classes and Methods
• Programming with Arrays and Classes
• Sorting Arrays
• Multidimensional Arrays
Motivation
• How to organize 100 Student objects?
• 100 different Student object names?
• Organize data for efficient access
– Class: different data types in one object
– Array: multiple objects of the same type
Overview
• An array
– a single name for a collection of data values
– all of the same data type
– subscript notation to identify one of the values
• A carryover from earlier programming languages
• More than a primitive type, less than an object
– like objects when used as method parameters and return
types
– do not have or use inheritance
• Accessing each of the values in an array
– Usually a for loop
Creating Arrays
• General syntax for declaring an array:
• Examples:
80-element array with base type char:
char[] symbol = new char[80];
pressure[3] = keyboard.nextInt();
System.out.println("You entered" + pressure[3]);
Some Array Terminology
Array name
temperature[n + 2]
Index - also called a subscript
- must be an int,
- or an expression that evaluates to an int
temperature[n + 2]
Indexed variable - also called an
element or subscripted variable
temperature[n + 2] Value of the indexed variable
- also called an element of the array
temperature[n + 2] = 32;
Programming Tip:
Do not count on default initial values for array elements
– explicitly initialize elements in the declaration or in a loop
Arrays, Classes, and Methods
An array of a class can This excerpt from the Sales Report program
be declared and the
in the text uses the SalesAssociate class
class's methods applied
to the elements of the to create an array of sales associates:
array.
public void getFigures()
create an array of {
SalesAssociates System.out.println("Enter number of sales associates:");
numberOfAssociates = SavitchIn.readLineInt();
SalesAssociate[] record =
each array element is new SalesAssociate[numberOfAssociates];
a SalesAssociate for (int i = 0; i < numberOfAssociates; i++)
variable {
record[i] = new SalesAssociate();
System.out.println("Enter data for associate " + (i + 1));
use the readInput record[i].readInput();
method of System.out.println();
SalesAssociate }
}
Arrays and Array Elements
as Method Arguments
• Arrays and array elements can be
– used with classes and methods just like other
objects
– be an argument in a method
– returned by methods
public static void main(String[] arg)
Indexed {
Scanner keyboard = new Scanner(System.in);a
Variables System.out.println("Enter your score on exam 1:");
int firstScore = keyboard.nextInt();
as Method int[ ] nextScore = new int[3];
int i;
Arguments double possibleAverage;
for (i = 0; i < nextScore.length; i++)
nextScore[i] = 80 + 10*i;
nextScore is for (i = 0; i < nextScore.length; i++)
an array of ints {
possibleAverage = average(firstScore, nextScore[i]);
System.out.println("If your score on exam 2 is "
an element of + nextScore[i]);
nextScore is System.out.println("your average will be "
+ possibleAverage);
an argument of
}
method }
average public static double average(int n1, int n2)
{
average return (n1 + n2)/2.0;
method definition } Excerpt from ArgumentDemo
program in text.
Passing Array Elements
public static void main(String[] arg)
{
SalesAssociate[] record = new SalesAssociate[numberOfAssociates];
int i;
for (i = 0; i < numberOfAssociates; i++)
{
record[i] = new SalesAssociate();
System.out.println("Enter data for associate " + (i + 1));
record[i].readInput();
}
m(record[0]);
}
public static void m(SalesAssociate sa)
{
}
When Can a Method Change an
Indexed Variable Argument?
• primitive types are “call-by-value”
– only a copy of the value is passed as an argument
– method cannot change the value of the indexed variable
• class types are reference types (“call by reference”)
– pass the address of the object
– the corresponding parameter in the method definition
becomes an alias of the object
– the method has access to the actual object
– so the method can change the value of the indexed
variable if it is a class (and not a primitive) type
Passing Array Elements
int[] grade = new int[10];
obj.method(grade[i]); // grade[i] cannot be changed
• In this example, the output from the command line above will be:
Hello Josephine Student
Using = with Array Names:
Remember They Are Reference Types
A value changed in a
The output for this code will be: is the same value
2 2 obtained with b
10 10
Using == with array names:
remember they are reference types
int i; a and b are both
3-element arrays of ints
int[] a = new int[3];
int[] b = new int[3];
all elements of a and b are
for(i=0; i < a.length; i++)
assigned the value 0
a[i] = 0;
for(i=0; i < b.length; i++) tests if the
b[i] = 0; addresses of a
if(b == a) and b are equal,
System.out.println("a equals b"); not if the array
else values are equal
System.out.println("a does not equal b");
The output for this code will be " a does not equal b"
because the addresses of the arrays are not equal.
Behavior of Three Operations
Primitive Class Entire Array
Type Type Array Element
Assignment Copy content Copy Copy Depends on
(=) address address primitive/
class type
Equality Compare Compare Compare Depends on
(==) content address address primitive/
class type
Parameter Pass by Pass by Pass by Depends on
Passing value reference reference primitive/
(content) (address) (address) class type
Testing Two
public static boolean equals(int[] a,
Arrays for {
int[] b)
Return an {
char[] c;
c = vowels();
Array for(int i = 0; i < c.length; i++)
System.out.println(c[i]);
}
public static char[] vowels()
• the address of {
char[] newArray = new char[5];
the array is newArray[0] = 'a';
passed newArray[1] = 'e';
newArray[2] = 'i';
• The local array newArray[3] = 'o';
name within the newArray[4] = 'u';
return newArray;
method is just }
another name } c, newArray, and
for the original the return type of
array vowels are
all the same type:
char []
Wrapper Classes for Arrays
• Arrays can be made into objects by creating a wrapper class
– similar to wrapper classes for primitive types
• The text shows an example of creating a wrapper class for an array of objects
of type OneWayNoRepeatsList
– the wrapper class defines two constructors plus the following methods:
addItem, full, empty, entryAt, atLastEntry, onList,
maximumNumberOfEntries, numberOfEntries, and
eraseList
Partially Filled Arrays
• Sometimes only part of an array has been filled with data
• Sequential search:
– start at the beginning of the array and proceed in sequence until either
the value is found or the end of the array is reached*
• if the array is only partially filled, the search stops when the last
meaningful value has been checked
– it is not the most efficient way
– but it works and is easy to program
* Or, just as easy, start at the end and work backwards toward the beginning
Example: Sequential Search of an Array
public boolean onList(String item)
{
boolean found = false;
int i = 0;
while ((! found) &&
(i < countOfEntries))
The onList method of {
OneWayNoRepeatsList if (item.equals(entry[i]))
sequentially searches the found = true;
array entry to see it the else
i++;
parameter item is in the }
array
return found;
}
Gotcha: Returning an
Array Attribute (Instance Variable)
• Access methods that return references to array instance variables cause
problems for information hiding.
Example: class …
{
private String[] entry;
…
public String[] getEntryArray()
{
return entry;
}
• There are many ways to sort a list, just as there are many ways to
search a list
• Selection sort
– one of the easiest
– not the most efficient, but easy to understand and program
Selection Sort Algorithm
for an Array of Integers
To sort an array on integers in ascending order:
1. Find the smallest number and record its index
2. swap (interchange) the smallest number with the first
element of the array
– the sorted part of the array is now the first element
– the unsorted part of the array is the remaining
elements
3. repeat Steps 2 and 3 until all elements have been placed
– each iteration increases the length of the sorted part
by one
Key:
Selection Sort Example smallest remaining value
sorted elements
1st iteration: smallest value is 3, its index is 4, swap a[0] with a[4]
before: 7 6 11 17 3 15 5 19 30 14
after: 3 6 11 17 7 15 5 19 30 14
2nd iteration: smallest value in remaining list is 5, its index is 6, swap a[1] with a[6]
3 6 11 17 7 15 5 19 30 14
3 5 11 17 7 15 6 19 30 14
10 33 100 1,024
• Arrays with more than two dimensions are a simple extension of two-
dimensional (2-D) arrays
Indexes 0 1 2 3 4 5
0 $1050 $1055 $1060 $1065 $1070 $1075
1 $1103 $1113 $1124 $1134 $1145 $1156
2 $1158 $1174 $1191 $1208 $1225 $1242
3 $1216 $1239 $1262 $1286 $1311 $1335
Row Index 3 4 $1276 $1307 $1338 $1370 $1403 $1436
(4th row) … … … … … … …
balance method in
class InterestTable
public static int balance(double startBalance, int years,
double rate)
{
double runningBalance = startBalance;
int count;
for (count = 1; count <= years; count++)
runningBalance = runningBalance*(1 + rate/100);
return (int) (Math.round(runningBalance));
}
Processing a 2-D Array:
for Loops Nested 2-Deep
• To process all elements of an n-D array nest n for loops
– each loop has its own counter that corresponds to an index
• For example: calculate and enter balances in the interest table
– inner loop repeats 6 times (six rates) for every outer loop iteration
– the outer loop repeats 10 times (10 different values of years)
– so the inner repeats 10 x 6 = 60 times = # cells in table
• Example: create a 2-D int array named b with 5 elements in the first
row, 7 in the second row, and 4 in the third row:
int[][] b = new int[3][];
b[0] = new int[5];
b[1] = new int[7];
b[2] = new int[4];
Programming Example:
Employee Time Records