Documente Academic
Documente Profesional
Documente Cultură
CITS1001
Fixed-size collections
ArrayList is used when the size of a collection
Arrays
An array is an indexed sequence of variables
Uses of arrays
Arrays are used when we have large numbers of identical
Declaring arrays
An array is declared using similar syntax to any other variable
int[] a;
Declares a to be a variable representing an array of ints
double[] temps;
Declares temps to be a variable representing an array of doubles
String[] names;
Declares names to be a variable representing an array of Strings
Student[] marks;
Declares marks to be a variable representing an array of Student objects
Creating Arrays I
An array is an object in a Java program
point to the array, but does not create the array itself
Hence the declaration
int[] a;
Creating Arrays II
In order to actually create the array, we must use the
0
a[0]
0
a[1]
0
a[2]
0
a[3]
0
a[4]
0
a[5]
0
a[6]
10
a[4] = 15;
a[2] = 7;
0
a[0]
0
a[1]
7
a[2]
-1
15
a[3]
a[4]
0
a[5]
17
a[6]
11
Indexing arrays
A lot of the power of arrays comes from the fact that
0
a[0]
0
a[1]
7
a[2]
5
a[3]
44
a[4]
0
a[5]
17
a[6]
12
13
14
15
16
17
Array literals
An array literal is written using {}
private int[] numbers = {3, 15, 4, 5};
declaration,
creation, and
initialization
18
Returning an array
Suppose we want to find the running sums of a
sums({2,5,8,3}) = {2,7,1,2}
19
Returning an array
Suppose we want to average each pair of elements of a
avs({2,6,8,2}) = {4,3}
20
Updating an array
Sometimes instead of creating a new array,
we want to update the old one
21
22
23
24
0
a
25
0
a
26
0
9
27
Aliasing
This is called aliasing
Basically one array with two names
It applies in the same way with any other
object-types too
Be careful with equality over arrays
In some applications we might want to use
aliasing deliberately
28
int x = 5;
System.out.println(x);
f(x);
System.out.println(x);
5
5
x is unchanged
29
int[] x = {5,3,1};
System.out.println(x[0]);
f(x);
System.out.println(x[0]);
5
666
x is unchanged
but x[0] is changed