Arrays and Methods
"They have computers, and they may have other weapons of mass
destruction."
-- Janet Reno
As with other reference types, arrays can be:
- passed as arguments to a method
- returned from a method
Arrays as Arguments
- Arrays can be used as arguments to methods like any
other type.
- Since arrays are references, the method can actually
change the array's elements.
Example:
public class
changeArray
{
public static void oops(int[] a)
{
int n = a.length; // notice that this
is NOT a method call!
int zero = a[0];
a[0] = a[n-1];
a[n-1] = zero;
} // what does this method do??
public static void main(String[] args)
{
int[] myArray = {1, 2, 3, 4};
oops(myArray);
for(int i = 0; i < myArray.length;
i++)
System.out.println(myArray[i]);
}
}
Output:
4
2
3
1
Exercise: Write
a
program
that
contains a method that takes an array of doubles, and
returns the sum of the array's elements. Test this method in your
program's main method.
Exercise: Write a method that
takes as its arguments an array of integers, and an integer value, and
returns the index of the first occurrence of that integer value in the
array. If the integer does not occur in the array, return -1.
Exercise: Write a swap() method that takes an array of integers, and
two integer indexes i and j, and swaps the position of the array
entries at index i and j. If one or both indices (i and j) are invalid,
the method should do nothing.
Exercise: Write a program that
reads 10 integers from the keyboard and stores them in an array. Write
a method called reverse that reverses the order of the elements in the
array. In the main method, print the array, call reverse, and then
print the array again.
Arrays as
Return Values
- When you want to return a sequence of values from a
method, use an array as the return type.
Example:
public class
genArray
{
public static int[ ] fillArray(int size)
{
// Creates array
containing integers 1 to size
int[ ] result = new
int[size];
for(int i = 0; i <
size; i++)
{
result[i] =
i+1;
}
return result;
}
public static void main(String[] args)
{
int[ ] a = fillArray(5);
for(int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
}
Output:
1
2
3
4
5
Exercise: Write a program that
includes a method that takes 2 integers and creates and returns an
array that contains all the integer values between them. That is, if
the integers passed to the method are -1 and 7, the method should
return an array that contains -1, 0, 1, 2, 3, 4, 5, 6, 7. In your main
method, call this method to create several arrays and then print them.
Useful Methods
for Arrays
java.lang.System
methods
static void
arraycopy(Object from, int fromIndex, Object to, int toIndex, int count)
java.util.Arrays
methods
sort(Type[ ] a)
sorts an array of type int, long, short, char, byte,
boolean, float or double into ascending order
binarySearch(Type[ ] a,
Type v)
a
is a sorted array of type int, long, short, char, byte, boolean, float
or double.
The binary search algorithm is used to search for
value v. If v is in a, then v's index is returned;
otherwise a negative value is returned.
equals(Type[ ] a, Object
other)
a is an array of type int, long, short, char, byte,
boolean, float or double.
This method returns true if other is an array of the
same type and size, and the elements in corresponding positions match.
It returns false otherwise.
fill(Type[] a, Type value)
Sets every entry in a to value.
toString(Type[] a)
returns a nice String representation of array a, e.g., [1, 2, 3]
copyOf(Type[] a, int
newSize)
returns a copy of array a with the
given size
Exercise: Write a program that
reads 15 floating point numbers from the keyboard, and stores these
numbers in an array. Print a message indicating the largest array
element and the smallest array element.
Searching Arrays
Search
Algorithms
- Linear Search
- Binary Search
Searching - locating
a particular value (the key)
in an array
Linear Search
- works well for small arrays or unsorted arrays
- looks at each entry, starting with first, until search
key is found or end of array is reached
- Returns either the index of the key, or a negative
value if the key does not appear in the array
public int
linearSearch(int[ ] theArray, int key)
{
for(int i = 0; i < array.length; i++)
if(array[i] = = key) return i;
return -1;
}
Algorithm Analysis:
If the array elements are unsorted, then on average the linear search
algorithm will compare the key to half the array elements.
So for an array of size n, linear search does n/2 comparisons in the
average case.
Binary Search
- requires a sorted array - the algorithm fails
completely on unsorted arrays
- eliminates half of the remaining array elements from
consideration after each comparison
- Searches the way you would search for a person's phone
number in a phone book:
- Compares the middle of the array elements to the key
- If they are equal, return index
- If not, and search key < middle array element,
search 1st half of the array
- Else search second half of the array
Example:
Search for key = 40 in array containing 2, 5, 7, 10, 15, 31, 40, 55
public int
binarySearch(int[ ] array, int key)
{
int low = 0, high = array.length - 1;
while(low <= high) // Search elements in
positions low to high
{
int mid = (low + high)/2; // index of
the middle element
if(array[mid] = = key) // compare
middle element in the search range to the key
return mid;
else if(array[mid] < key) //
Search top half
low = mid + 1;
else // Search bottom half
high = mid - 1;
}
return -1;
}
Exercise: When binary
search is carried out on array
[3, 8, 10, 30, 35, 37, 40, 45, 50, 58] and key = 10, how many array
elements are compared to the key?
A. 1
B. 2
C. 3
D. 4
E. 5
Methods and Arrays
Recall: When you pass an array or other object to a method, you
are actually passing the address of that object. So the method can
modify the object.
Example: Write a method makeArray()
that takes an integer n
(as its parameter), and creates and returns an array that contains the
integers 0, 1, ..., |n|-1.
Then
write
a
main()
method that reads an integer k from the
user, calls makeArray(k),
and
prints
the
array that is returned.
public static int[]
makeArray(int n) {
int size = Math.abs(n);
// finish the method...
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Array size? ");
int cap = scan.nextInt();
int[] newArray = makeArray(cap);
for(int j = 0; j < newArray.length; j++)
System.out.println(newArray[j]);
}
Exercise: Write a method that takes an array of integers, and
increments the first and last elements of the array. Write a main
method that calls this method, printing the array after the method
call.
Questions: Consider the
following program:
import java.util.*;
public class Ref {
public static void changePrim(int n, int m) {
int temp = n;
n = m;
m = temp;
}
public static void changeRef(int[] arr) {
int temp = arr[0];
arr[0] = arr[arr.length-1];
arr[arr.length-1] = temp;
}
public static void main(String[] args) {
int n = 4;
int m = 5;
System.out.println("n: " + n + ",
m: " + m);
changePrim(n, m);
System.out.println("n: " + n + ",
m: " + m); // line
1
int[] a = {1, 2, 3, 4};
System.out.println(Arrays.toString(a));
changeRef(a);
System.out.println("" +
Arrays.toString(a)); // line
2
}
}
1. What is the output from line
1? 2. What is the
output from line 2?
A. n: 4, m:
5
A.
[1,
2, 3, 4]
B. n: 0, m:
0
B.
[4,
2, 3, 1]
C. n: 5, m:
4
C.
[4,
3, 2, 1]
D.
[0,
0, 0, 0]
for-each loop
If we only want to examine or display all the elements in an array in
order from first to last (e.g., the previous exercise), we can use a
different loop construct:
- an enhanced for loop
(or for-each loop).
Example: Use an enhanced for loop to print an array's
entries.
int[] arr =
{1, 2, 3, 4, 5};
for(int value : arr)
System.out.println(value);
Output:
1
2
3
4
5
Exercise: Write a method that takes an array of integers and
returns the largest array element.
Note: We cannot change array entries in the body of
a for-each loop. This does not work as expected:
int[] arr =
{1, 2, 3, 4, 5};
for(int value : arr) {
value++;
}
// arr is unchanged after the for-each loop is executed
Review Questions:
1. What is the output of the following code?
int[] a = {4,
5, 6};
for(int i = 0; i < a.length; i++) {
a[i]++;
}
System.out.println(a[2]);
A. 4
B. 5
C. 6
D. 7
E. An exception is thrown.
2.
What is the output of the following code?
int[] a = {4,
5, 6};
for(int n : a) {
n++;
}
System.out.println(a[2]);
A. 4
B. 5
C. 6
D. 7
E. An exception is thrown.
More Array Traversal
If we want to reverse an array, we can either modify the original array
so that it is reversed, or produce a new array that is the reverse of
the original, leaving the first array unchanged.
Exercise: Write a method that takes an integer
array as its argument, and returns the reverse array, leaving the
argument unchanged.
Exercise: Write a method shuffle()
that takes an integer array as its argument, and modifies the array by
shifting all entries one place to the right and moving the last entry
to the first position in the array.
int[] a = {2, 3, 4};
shuffle(a); // now a is {4, 2, 3}
The value null
null
is a value that can be assigned to a reference variable to indicate
that the variable has not been assigned the address of an object.
String str =
null;
int[] arr = null;
This use of null
allows us to do some error checking: we can write code that checks
whether or not the reference variable has been initialized with this
type of comparison:
if(str == null)
or
if(arr
!=
null)
Arrays of
Objects
To create an array of objects:
1. Create the array's reference variable.
Ex: Random[]
r;
2. Allocate the array of object references.
r = new
Random[3];
3. Allocate memory for each array entry.
for(int i = 0; i < 3; i++)
r[i] = new Random();
Example: Create an array of five String
objects. Initialize the
array entries to be: "elvis0", "elvis1", ..., "elvis4". Use a for-each
loop to print the Strings in
the array. Then write a method reverseConcat()
that takes your String
array as its parameter, and returns a String that
contains the concatenation of all the Strings in
reverse order, e.g., "elvis4elvis3elvis2elvis1" is returned for the
array in our example.