2/22/2020
Arrays
Liang, Introduction to Java programming, 11th Edition, © 2017 Pearson Education, Inc.
All rights reserved
By: Mamoun Nawahdah (Ph.D.)
2020
Introducing Arrays
Array is a data structure that represents a
collection of the same types of data.
1
2/22/2020
Declaring Array Variables
datatype[] arrayRefVar;
Example:
double[] myList;
datatype arrayRefVar[]; // This style is allowed, but not preferred
Example:
double myList[];
Creating Arrays
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];
myList[0] references the 1st element.
myList[9] references the last element.
2
2/22/2020
Declaring and Creating in 1 Step
datatype[] arrayRefVar = new datatype[arraySize];
double[] myList = new double[10];
datatype arrayRefVar[] = new datatype[arraySize];
double myList[] = new double[10];
The Length of an Array
Once an array is created, its size is fixed.
It cannot be changed.
You can find its size using:
arrayRefVar.length
For example:
myList.length returns 10
3
2/22/2020
Default Values
When an array is created, its elements
are assigned the default value of :
0 for the numeric data types.
'\u0000' for char types.
false for boolean types.
Indexed Variables
The array elements are accessed through
the index.
The array indices are 0-based, i.e., it starts
from 0 to arrayRefVar.length-1.
Each element in the array is represented
using the following syntax, known as an
indexed variable:
arrayRefVar[index];
8
4
2/22/2020
Using Indexed Variables
After an array is created, an indexed variable
can be used in the same way as a regular
variable.
For example, the following code adds the
value in myList[0] and myList[1] to myList[2]:
myList[2] = myList[0] + myList[1];
Array Initializers
Declaring, creating, initializing in 1 step:
double[] myList = {1.9 , 2.9 , 3.4 , 3.5};
This shorthand notation is equivalent to the
following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5; 10
5
2/22/2020
CAUTION
Using the shorthand notation, you have to
declare, create, and initialize the array all in
one statement.
Splitting it would cause a syntax error.
For example, the following is wrong:
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < values.length; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
12
6
2/22/2020
Initializing arrays with input values
double[] myList = new double[10];
Scanner input = new Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0 ; i < myList.length ; i++)
myList[ i ] = input.nextDouble();
13
Initializing arrays with random values
for (int i = 0; i < myList.length; i++)
myList[i] = Math.random() * 100;
Printing arrays
for (int i = 0; i < myList.length; i++)
System.out.print(myList[i] + " ");
14
7
2/22/2020
Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++)
total += myList[i];
Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++)
if (myList[i] > max)
max = myList[i];
15
Random Shuffling
16
8
2/22/2020
Shifting Elements
17
Enhanced for Loop (for-each loop)
JDK 1.5 introduced a new for loop that enables you to traverse
the complete array sequentially without using an index variable.
For example, the following code displays all elements in the array
myList:
for (double value : myList) System.out.println(value);
In general, the syntax is:
for (elementType value : arrayRefVar) {
// Process the value
}
You still have to use an index variable if you wish to traverse the
array in a different order or change the elements in the array.
18
9
2/22/2020
Problem: Deck of Cards
The problem is to write a program that picks
four cards randomly from a deck of 52 cards.
All the cards can be represented using an array
named deck, filled with initial values 0 to 51, as
follows:
int[] deck = new int[52];
// Initialize cards
for (int i = 0; i < deck.length; i++)
deck[i] = i;
Problem: Deck of Cards, cont.
10
2/22/2020
Problem: Deck of Cards, cont.
Problem: Deck of Cards
This problem builds a foundation for future
more interesting and realistic applications:
https://liveexample.pearsoncmg.com/dsanimation/24Point.html
11
2/22/2020
Copying Arrays
Often, in a program, you need to duplicate an array or a
part of an array. In such cases you could attempt to use
the assignment statement (=), as follows:
list2 = list1;
23
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
for (int i = 0; i < sourceArrays.length; i++)
targetArray[i] = sourceArray[i];
24
12
2/22/2020
The arraycopy Utility
System.arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);
Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);
25
Passing Arrays to Methods
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
Invoke the method
int[] list = {3, 1, 2, 6, 4, 2};
printArray(list);
26
13
2/22/2020
Anonymous Array
The statement
printArray(new int[]{3, 1, 2, 6, 4, 2});
Creates array using the following syntax:
new dataType[]{literal0, literal1, ..., literalk}
There is no explicit reference variable for
the created array.
Such array is called an anonymous array.
27
Pass by Value
For a parameter of a primitive type value, the
actual value is passed.
Changing the value of the local parameter
inside the method does not affect the value of
the variable outside the method.
For a parameter of an array type, the value of
the parameter contains a reference to an array;
this reference is passed to the method.
Any changes to the array that occur inside the
method body will affect the original array that
was passed as the argument.
28
14
2/22/2020
Simple Example
public class Test {
public static void main(String[] args) {
int x = 1;
int[] y = {1,2,3,4,5};
m(x, y);
System.out.println(" x is " + x );
System.out.println(" y[0] is " + y[0] );
}
public static void m(int number, int[] numbers) {
number = 1001;
numbers[0] = 5005;
}
}
29
Returning an Array from a Method
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i=0, j=result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
30
15
2/22/2020
Linear Search
The linear search approach compares the key
element, key, sequentially with each element in
the array list.
The method continues to do so until the key
matches an element in the list or the list is
exhausted without a match being found.
If a match is made, the linear search returns
the index of the element in the array that
matches the key.
If no match is found, the search returns -1.
31
From Idea to Solution
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++)
if (key == list[i]) return i;
return -1;
}
Trace the method:
int[] list = {1, 4, 4, 2, 5, -3, 6, 2};
int i = linearSearch(list, 4); // returns 1
int j = linearSearch(list, -4); // returns -1
int k = linearSearch(list, -3); // returns 5
32
16
2/22/2020
The Arrays.binarySearch Method
Since binary search is frequently used in programming,
Java provides several binarySearch methods for
searching a key in an array of int, double, char, short,
long, and float in the java.util.Arrays class.
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
System.out.println("Index is " + Arrays.binarySearch(list, 11));
char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'};
System.out.println("Index t is " + Arrays.binarySearch(chars, 't'));
For the binarySearch method to work, the array must
be pre-sorted in increasing order.
33
Selection Sort
Selection sort finds the smallest number in the list and places it
first. It then finds the smallest number remaining and places it
second, and so on until the list contains only a single number.
34
17
2/22/2020
From Idea to Solution
Selection sort algorithm:
for (int i = 0; i < list.length; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i+1..listSize-1]
}
35
The Arrays.sort Method
Java provides several sort methods for sorting an array
of int, double, char, short, long, and float in the
java.util.Arrays class.
For example, the following code sorts an array of
numbers and an array of characters:
double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};
java.util.Arrays.sort(numbers);
char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};
java.util.Arrays.sort(chars);
36
18
2/22/2020
main Method is just a Regular Method
You can call a regular method by passing actual
parameters.
You can pass arguments to main.
For example, the main method in class B is
invoked by a method in A, as shown below:
37
Command-Line Parameters
class TestMain {
public static void main(String[] s) {
...
}
}
In the main method, get the arguments from
s[0], s[1], ..., s[n], which corresponds to arg0,
arg1, ..., argn in the command line.
38
19
2/22/2020
Problem: Calculator
Objective: Write a class “Calculator” that
will perform binary operations on integers.
The class receives three parameters: an
operator and two integers as follow:
39
Declare/Create 2D Arrays
// Declare array refvar
dataType[][] refVar;
// Create array and assign its reference to variable
refVar = new dataType[10][10];
// Combine declaration and creation in one statement
dataType[][] refVar = new dataType[10][10];
// Alternative syntax
dataType refVar[][] = new dataType[10][10];
40
20
2/22/2020
Creating 2D Arrays
int[][] matrix = new int[3][2];
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() * 100);
41
Lengths of 2D Arrays
int[][] x = new int[3][4];
42
21
2/22/2020
Lengths of 2D Arrays, cont.
int[][] array = { array.length
{1, 2, 3}, array[0].length
{4, 5, 6}, array[1].length
{7, 8, 9}, array[2].length
{10, 11, 12} array[3].length
};
array[4].length ArrayIndexOutOfBoundsException
43
Declaring, Creating, and Initializing
Using Shorthand Notations
You can also use an array initializer to declare,
create and initialize a 2-dimensional array.
For example:
int[][] array = {
{1, 2, 3} ,
{4, 5, 6} ,
{7, 8, 9} ,
{10, 11, 12}
};
44
22
2/22/2020
Ragged Arrays
Each row in a 2D array is itself an array. So, the rows can
have different lengths.
Such an array is known as a ragged array.
For example:
45
Printing Arrays
for (int r = 0; r < arr.length; r++) {
for (int c = 0; c < arr[r].length; c++)
System.out.print(arr[r][c] + " ");
System.out.println();
}
46
23
2/22/2020
What is Sudoku?
Checking Whether a Solution Is Correct?
47
Multidimensional Arrays
Occasionally, you will need to represent
n-dimensional data structures.
In Java, you can create n-dimensional arrays for
any integer n.
The way to declare two-dimensional array
variables and create 2-dimensional arrays can be
generalized to declare n-dimensional array
variables and create n-dimensional arrays for n > 2.
48
24
2/22/2020
Multidimensional Arrays
double[][][] scores = {
{{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},
{{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}},
{{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}},
{{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}},
{{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}},
{{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}};
49
25