06Arrays
06Arrays
Programming Techniques
Arrays
Agenda & Reading
Topics:
Introduction
Primitive Types vs. Reference Types
Arrays
Multidimensional Arrays
Arrays of Objects
Reading
Java how to program Late objects version (D & D)
Chapter 6
The Java Tutorial
Arrays
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
http://www.tutorialspoint.com/java/java_arrays.htm
2 Lecture06
1.Introduction
Data structures — collections of related data items.
Array objects — data structures consisting of related data items of
the same type.
Make it convenient to process related groups of values.
Remain the same length once they’re created.
Enhanced for statement : allows a program to access the data in
an array more easily than does the counter-controlled for
statement.
Use variable-length argument lists to create methods that can
be called with varying numbers of arguments.
Demonstrate how to process command-line arguments in
method main.
static methods of class Arrays from the java.util package.
ArrayLists are similar to arrays but provide additional
functionality,
3 Lecture06
2.Primitive Types vs. Reference Types
Java is a strongly typed language.
Java requires all variables to have a type.
Java’s types are divided into primitive types and
reference types.
Primitive types:
boolean, byte, char, short, int, long, float and double.
A variable of a primitive type is directly associated with a
int intA = 15;
memory location storing the value of the int variable.
intB = 10;
4 Lecture06
2.Primitive Types vs. Reference Types
Reference Types:
Any data type that is not a primitive type is a reference
type
Programs use variables of reference types (normally called
references) to store the addresses of objects in the
computer’s memory.
Such a variable is said to refer to an object in the program.
If a variable is not initialized explicitly, the variable is given
the special value null.
6 Lecture06
int[] ages = new int[10];
String[] names = new String[10];
3.Arrays
An array is a group of variables (called elements)
containing values that all have the same type.
The type of an array is determined by its element
type, which is specified when the array is instantiated.
Arrays are objects and thus are of a reference type.
Elements can be either primitive types or reference types.
Default values: (int:0; String: null; boolean:false)
The length of an array can be obtained from the array
object’s length variable
An array’s length is fixed when it is created (determines
the amount of memory allocated) and cannot be changed
unless the arraySystem.out.println(courseMarks.length);
is redeclared.
7 Lecture06
0
Array Name Index Value 1
8 Lecture06
3.Arrays
Declaring & Creating Arrays
The three steps for creating an array are
Declaring an Array int courseMarks[];
Syntax: <type><name>[]; //or String[] args;
int[4] courseMarks;
<type>[] <name>;
Specify the size in
No memory space allocated array declaration is a
No length specified syntax error
The array has not been initialized
Creating a New Array
<name> = new <type>[Length]; courseMarks = new int[10];
Syntax:
specify the type of the array elements and the number of elements as part of an
array-creation expression that uses keyword new.
returns a reference that can be stored in an array variable.
Note: memory space allocated, length specified, initialized to default values
Creating & Initializing elements
create an array and initialize its elements with an array initializer — a comma-
separated list of expressions enclosed in braces.
i.e. counts the number of initializers in the list to determine theint[]{26,73,55,97};
size of the array
courseMarks = new
Syntax: <name> = new <type> { values };
9 Lecture06
3.Arrays
Creating Arrays
Combine declaration and creation
The first two steps of creating an array can be combined as one:
int[] courseMarks = new int[10];
11 Lecture06
L06Code.jav
3.Arrays a
Example 1
Example 1:
creates a 10-element array and assigns to each element
one of the even integers from 2 to 20 (2, 4, 6, …, 20).
ARRAY_LENGTH: is a constant.
Constant variables must be initialized before they’re used and
cannot be modified thereafter.
final int ARRAY_LENGTH = 5;
int[] array = new int[ARRAY_LENGTH];
12 Lecture06
3.Arrays
Enhanced for Statement
Iterates through the elements of an array without
using a counter, thus avoiding the possibility of
“stepping outside”
for (parameter the array.
: arrayName)
statement
Syntax:
where parameter has a type and an identifier, and
arrayName is the array through which to iterate.
It can be used only to obtain array elements—it
cannot be used to modify elements.
Note: No error message generated, the values are simply
unchanged 2
for (int value: array) 4
If you
valueneed
+= 2; to modify elements, use the standard for
6 loop
for (int value: array) 8
System.out.printf("%5d%n", value); 10
13 Lecture06
L06Code.jav
3.Arrays a
When you run a program from the command line, all words after the
class name will be passed to the main method in the args array.
>java TestArray Hello World
The following main method in the class TestArray will print out the first
two arguments it receives:
public static void main(String[] args) { Output
for (int i=0; i<args.length; i++) :
System.out.println(args[i]);
} Hello
World
14 Lecture06
3.Arrays
Testing for Equality
The following example creates two arrays of ints.
int[] a = new int[] {1, 2, 3}; a b
int[] b = new int[] {1, 2, 3}; 0 0 0 0
1 1 1 1
2 2
2 2
Comparison “==”
Compares references, not values. The use of == with array/object
references is generally limited to if two references are to the same
object
if (b == a)
Not Equal
System.out.println("Equal");
else
System.out.println("Not Equal");
Must create an
object first
Not Equal
17 Lecture06
Exercise 1
What is the output of the following code fragment?
int[] array = {0, 2, 4};
for (int value: array)
value += 2;
System.out.println(Arrays.toString(array));
18 Lecture06
L06Code02.jav
3.Arrays a
Pass-by-value
All arguments are passed by value in method calls in Java.
A method call can pass TWO types of values to a method—
copies of primitive values and copies of references to objects.
Objects themselves cannot be passed to methods.
Case 1: primitive types: (int, double, float.. etc)
a copy of the argument’s value is passed to the called method.
changes to the called method’s copy do not affect the original variable’s
value in the caller.
public static void changeMyNumber(int justACopy){
justACopy = 10;
System.out.println("justACopy = "+justACopy);
}
Pass-By-Value
Case 2: Reference Types (StringBuffer, array… etc)
i.e. a copy the object’s reference is passed to the called method
an object’s reference is passed by value, a method can still interact with
the referenced object by calling its public methods using the copy of the
object’s reference.
The parameter in the called method and the argument in the calling
method refer to the same object in memory.
We can modify the object and have the changes reflected in the outer
scope.
public static void changeMyString(StringBuffer justACopy) {
justACopy.append("++"); ++
myString myNumb
0x25a1 er
12345
System.out.println("justACopy = "+ justACopy); c
}
copy of the object’s reference to
public static void myMethod2() { justACopy
Pass-By-Value
Case 3: Reference Types (StringBuffer, array… etc)
i.e. a copy the object’s reference is passed to the called method
If you modify a reference-type parameter so that it refers to another
object, only the parameter refers to the new one.
changes to the called method’s copy do not affect the original variable’s
value in the caller.
public static void makeNewString(StringBuffer justACopy) {
System.out.println("justACopy = "+justACopy);
}
23 Lecture06
L06Code02.jav
3.Arrays a
7
int[][] x = new int[5][7];
columns:
5 rows
25 Lecture06
4.Multidimensional Arrays
2-Dimensional Arrays
Declaration & Initialization 2-D arrays
Syntax for 2-D arrays is similar to 1-D arrays
<type>[][] <name> = new <type>[rows][columns];
Example 1:
int[][] x = new int[5][7];
Example 2:
int[][] x = new int [4][];
a1
To create copies of an existing 1-dimensional arrays,
0 10 we
int[][] a4={a1.clone(), a2.clone()};
can use the clone method a2
1 12
a4 1 1 1 0 20 2 14
0
0 2 4
1 2 2 2 1 22
0 2 4
2 24
27 Lecture06
4.Multidimensional Arrays
Length Variables
Using the Length Variable:
arrayName.length
returns the number of rows in the array
arrayName[rowToGet].length
returns the number of columns in row "rowToGet"
int[][] x = new int[5][7];
System.out.println(x.length);
System.out.println(x[0].length);
5
Note: 7
28 Lecture06
4.Multidimensional Arrays
L06Code03.jav
a
Using 2D Arrays
Accessing elements
To access elements, we use pretty much the same technique as a
1D array
System.out.println(myArr[rowToGet][colToGet]);
29 Lecture06
4.Multidimensional Arrays
Cloning of Multi-D Arrays
It is shallow clone only
Remember that multi-dimensional arrays in Java are arrays of arrays.
Cloning only generates a copy of the root array
Note: a5[0] and a5[1] from an 1-dimensional array that store the
memory location m0 and m1 of two 1-dimensional arrays. If we clone
a5, then we only create a new 1-dimensional array that stores m0 and
m1.
30 Lecture06
4.Multidimensional Arrays
Ragged Arrays
Ragged arrays have rows of unequal length
Each row has a different number of columns, or entries
Declaration & Initialization a ragged array
<type>[][] <name> = new <type>[rows][];
<name>[0] = new <type>[colCountForRow1];
… int[][] b1 = new int[2][ ];
b b1[0] = new int[]{1, 2, 3, 4, 5};
0 0 b1[1] = new int[]{1, 2, 3};
int[][] b; 0
b = new int[3][]; 0 0 0
1
b[0] = new int[2]; b 1 2 3 4 5
2 0 0
b[1] = new int[3];
b[2] = new int[1]; 1 1 2 3
33 Lecture06
L06Code03.jav
4.Multidimensional Arrays a
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
34 Lecture06
int[][] grid = { { 3, 5, 6, 9 },{ 2, 6, 9, 4 } };
Exercise 2 int len;
len = grid.length;
for(int row=0; row < len; row++) {
for(int col=0; col < len; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}
35 Lecture06
5.Array of Objects
Apart from arrays of primitive types we can have arrays of reference
types (objects)
p
Creating an array of Point 0
x:10
Syntax: y:20
Create the array
1 x:20
<class>[]Point[]
<name> p == new
new <class>[Length];
Point[3];
y:30
2
Note: Memory space are allocated for the array NULL
Create the object element
<name>[row] = new <class>();
p[0] = new Point(10, 20);
p[1] = new Point(20, 30);
Note:
In an array of reference types not the objects are stored in the array, but
references to the objects.
The objects themselves have to be created and memory space has to be
allocated for them separately.
The element are initialized with the null reference.
36 Lecture06
L06Code04.jav
a
5.Array of Objects
Using Array of Objects
Accessing
To access all components of an array of reference types
we can use the same code that we have used for
primitive types
A for loop is used to print out values. java.awt.Point[x=10,y=20]
for (int i=0; i<2; i++)
System.out.println(p[i].toString()); java.awt.Point[x=20,y=30]
(10,20)
(20,30)
Exception in thread "main" java.lang.NullPointerException ...
37 Lecture06
5.Array of Objects L06Code04.jav
a
The variable copy holds a copy of the reference held in the variable
p. There is still only one copy of the array.
Thus changing the object pointed to by one of the variables will also
cause the contents of the other variable to change (since the same
object in memory is being altered).
copy[0].x = 100;
for (int i=0; i<copy.length; i++) java.awt.Point[x=100,y=20]
System.out.println(p[i].toString()); java.awt.Point[x=20,y=30]
java.awt.Point[x=30,y=40]
38 Lecture06
L06Code04.jav
a
5.Array of Objects
Copying Arrays of Objects
An array can be copied to reproduce an exact copies (or part) of the
original by using the System.arraycopy method
However, if the array elements are reference variables, both source and
destination now refer to the same object (pointing to the same physical
object in memory)
p x:10 -
Point[] p = new Point[3]; 0 >100
p[0] = new Point(10, 20);
p[1] = new Point(20, 30); y:20 cop
1 x:20 0 y
p[2] = new Point(30, 40);
y:30
Point[] copy = new Point[2]; 2 1
System.arraycopy(p,0, copy, 0, 2); x:30
Y:40
Thus changing the object pointed to by one of the variables will also cause
the contents of the other variable to change (since the same object in
memory is being altered).
copy[0].x = 100;
for (int i=0; i<copy.length; i++) java.awt.Point[x=100,y=20]
System.out.println(p[i].toString()); java.awt.Point[x=20,y=30]
39 Lecture06
L06Code04.jav
a
5.Array of Objects
Cloning Arrays of Objects
Shallow Clone
An array can be cloned to reproduce an exact copies of
the original
It allocates space to hold the same size as the original
It makes copies of the original and has the same problem as
before (pointing to the same physical object in memory)
40 Lecture06
L06Code04.jav
5.Array of Objects a
Deep Clone
A deep copy is copy that contains the complete data of
the original object, allowing it to be used independently of
the original object
Clone the array
Walk through each element in the new array
Clone the element in the array to produce a new copy
dest[0].x = 100;
System.out.println(q[0].toString()); java.awt.Point[x=10,y=20]
41 Lecture06
Advantages & Disadvantages
Advantages
Easy to specify (declaration, allocation of memory space,
initialization can all be done in one line of code)
Direct access to any element via the index
Fast Access
Disadvantages
A potential disadvantage of arrays is the need to know
the size at time of allocation
Careful design is required to make sure that the array
will be large enough to hold the largest possible group of
data
42 Lecture06
Exercise 3
Write a program that simulates rolling a pair of dice. Each die can
have the values of 1 to 6 and the sum of the dice can have values
from 2 to 12. Use a one-dimensional array to tally the number of
times each possible sum appears. The application should roll the
dice 36,000 times. Display the results in a tabular format.
int[] totals = new int[13];
int dice1, dice2;
SecureRandom randomNumbers = new SecureRandom(); Sum Frequency Percentage
2 1021 2
for (int roll = 1; roll <= 36000; roll++) { 3 1919 5
4 3032 8
5 3983 11
6 4944 13
7 6045 16
} 8 5023 13
9
System.out.printf("%3s%12s%12s\n","Sum", "Frequency", "Percentage"); 4051 11
for (int k = 2; k < totals.length; k++){ 10 2988 8
11 / (360));
System.out.printf("%3d%12d%12d%n", k, totals[k], totals[k] 1972 5
12 1022 2
43 Lecture06
Exercise 4 int[] array = {0,0,0,0,0,0,1,2,4,2,1};
System.out.println();
}
44 Lecture06