Arrays in Java notes

advertisement
Notes: Arrays in Java
In Java, an array is an indexed (or numbered) list of items that are all of the same data type.

The type of the individual elements in the array is called the base type of that array. The
base type of an array can be any legal Java type – a primitive type or a class.

Java arrays are objects. This means that arrays are created using the new operator.

No variable can ever hold an array, a variable can only refer to it.
Since int[ ] is a class, it can be used to declare variables:
int[] list; // creates a variable named list of type int[]
This variable is capable of referring to an array of ints, but initially its value is null. Use the new
operator to create a new array object, which can then be assigned to list.
The syntax for using new with arrays is:
<variable name> = new int[ array length];
For example:
list = new int[5];
// creates an array of five integers
lis t:
(5)
lis t.le ngth
0
lis t[0]
0
lis t[1]
0
lis t[2]
0
lis t[3]
0
lis t[4]
The array obje ct contains 5 inte ge rs
calle d lis t[0] e tc.
It als o has lis t.le ngth w hich give s the
num be r of ite m s in the array.
Note : lis t.le ngth cannot be change d.
The s tate m e nt "lis t = ne w int[5]";
cre ate s an array w hich can hold
5 ints , and s e ts lis t to re fe r to it
The number of items in an array is called the length of the array. The length of the array list can
be referred to as list.length and in this case would be 5.
The position number of the item in the array is called the index (or subscript) of that item. The
index of the first item in an array is always 0. If the length of the array is N then the index of the
last element is N-1. Once an array has been created its length cannot be changed.
The syntax for referring to an item in an array is array-variable [integer-expression], so
list[0] would refer to the first element in the array list, and list[4] the last if an array list had a
length of 5.
In Java, once an array is created it is always filled with a known or default value of the base type.
For example:
Claremont College 2015, based on Rosny College, 2009
Page 1 of 8

integers (int, double, etc.) - 0 (zero)

boolean - false

char - the character with Unicode number zero

Objects - null
Each item in an array can be used just like a variable:

values can be assigned to it

it can be used in expressions e.g. total = total + list[i]
e.g. total = total + list[i*3]

it can be passed as a parameter in subroutines.
e.g. list[1] = 46.4
To print out the items in an array, list, using the paint method:
for (int i = 0; i < list.length; i++)
{
g.drawString(“” + list[i], xpos, ypos);
xpos = xpos + 10;
}
This loop will end after painting list[4], because once i = 5 it will no longer be less than list.length
(of 5 in this case).
There are 2 possible errors that can occur when accessing an array:

A null pointer error - will occur if the value of the list is null, so list does not even refer to
an array. Trying to access say list[i] will produce this error.

Array index out of bounds error - will occur if list does refer to an array but the value of
the index is outside the legal range of values (in our example if i < 0 or if i > = list.length).
You can declare and instantiate an array variable in one step:
int[] list = new int[5];
and the array items will have the default values of e.g. zero for integers.
You can also declare, instantiate and initialise an array with a specific list of values:
int[]
list = { 1, 5, 7, 8, 12, 45 };
where the new list has the 6 values above, list points to this new array and list.length is known
to be 6.
The values used to initialise an array do not have to be constants. That is, they can be variables
or expressions, as long as their values are of the same base type.
int three = 3;
int[] list = { 1, 5*2, three, 8, 12, 45 };
You can assign a new value to an array variable that has been declared earlier. For example:
list = new int[ ] { 12, 24, 36, 48, 60, 66};
Note: Although correct Java syntax ( <type-name> <variable-name> ), would have us declare
arrays like this…
int[] list;
…you may something, however is sometimes written as
int list[];
This is a hangover from C, C++, and Pascal syntax.
Claremont College 2015, based on Rosny College, 2009
Page 2 of 8
Array processing techniques
Processing an array means applying the same operation to each new item in the array – usually
with a for loop.
Remember that the loop can only be repeated up to a.length–1 times because otherwise there
would be an “array out of bounds error”.
Sum the contents of an array
int [ ] a
= {6, 7, 9, 12, 4};
public void init( );
{
total = 0;
// total starts at 0
for ( int i = 0; i < a.length; i = i + 1 )
total = total + a[i] ;
}
Count items in an array
To count the number of items in an array that meet a certain condition (e.g. that the items are
even numbers).
int [ ] a = {6, 7, 9, 12, 4};
public void init( );
{
count = 0;
// count starts at 0
for ( int i = 0; i < a.length; i = i + 1 )
{
if ((a[i] % 2) == 0)
count = count + 1;
}
}
To count the number of times an item is the same as the next item in the array a use the code
above replacing if ((a[i] % 2) == 0) with if (a[i] == a[i+1])
To find the largest (or smallest) element of an array
To find the largest (or smallest) item you create a variable called max (or min) and initially set it
to the value of the first item in your array a.
double max = a[0]; min = a[0];
for ( int i = 0; i < a.length; i = i + 1 )
{
if (a[i] > max) or if (a[i] < min)
max = a[i];
min = a[i];
}
// at the end of this loop max is the largest item in the array a or
// min would have the smallest.
Searching an array using binary search
Binary search works on a sorted array. Check if item being searched for is greater than or less
than a middle value. You can then eliminate half of the array from being searched. Progressively
halve the part of the array to be searched, until the item is found, or you find the item is not
there.
Claremont College 2015, based on Rosny College, 2009
Page 3 of 8
Making a copy of an array
In some computer languages it is possible to make a copy of one array using:
double[] b = a;
This is not correct in Java since all it does is declare a new array
variable and make it refer to the same object to which a refers.
i.e. a change to a[i] will make the same change to b[i] as well !!!
To make a new array b that is a copy of a, you must make a new array object and copy each of
the individual items from a into the new array b.
double[] b = new double[a.length]; // make a new array object the same size as a.
for (int i = 0; i < a.length; i = i + 1)
b[i] = a[i]; // move a copy of a[i] into b[i]
It is possible to only partially fill an array with useful data but you must keep a count of the
number of items in the array.
Note:
Objects of type String contain an array whose components are of type char.
To convert an array of char to a String Object and vice versa use the following:
char[ ] ch1 = {‘o’,‘b’,‘j’,‘e’,‘c’,‘t’}; //
//
String str1 = new String(ch1);
//
String str2 = new String(ch1, 1, 4);
//
char[] ch2 = str2.toCharArray( );
//
an array of characters is declared
and instantiated
str1 is the String “object”
str2 is the substring “bjec”
ch2 now contains {‘b’,‘j’,‘e’,‘c’};
Sorting an array
There are a number of different sorting strategies. We will look at the bubble sort. When sorting
items such as integers in an array a, you need to compare a[i] and a[i + 1]. To swap two values
around in the array you need to have another variable called hold to temporarily hold one of
these values. See below:
if (a[ i ] > a[i + 1])
{
hold = a[ i ];
a[ i ] = a[i + 1];
a[i + 1] = hold;
}
A bubble sort requires you to progressively compare elements next to each other in an array,
and (if you are sorting into ascending order) to place the lower number in the position with the
lower index.
Claremont College 2015, based on Rosny College, 2009
Page 4 of 8
// Sorting an array into order using the bubble sort method.
public class sort extends Applet
{
int a[ ] = {6, 5, 4, 3, 2, 1};
boolean finished;
int i, j, xpos, hold;
public void paint(Graphics g)
{
//sort array into order
while (finished == false)
{
finished = true;
for(i = 0; i < a.length - 1; i++)
{
if (a[i] > a[i+1])
{
hold = a[i];
a[i] = a[i+1];
a[i+1] = hold;
finished = false;
}
}
}
//output sorted array
xpos=100;
g.drawString("Sorted Array is",20,80);
for(j=0;j<=a.length-1;j++)
{
g.drawString(a[j]+"",xpos,80);
xpos = xpos+30;
}
}
}
To bubble sort an array of strings rather than integers.
Use as your array a:
String a[ ] = {“Greg”, “Geoff”, “Anthony”, “Murray”, “Dorothy”, Wags, “Henry”};
In the bubble sort algorithm, when comparing 2 items which are strings, you cannot use if (a[ i ]
> a[i + 1]) which is what you used for integers, use a[i].compareTo(a[i+1])
a[i].compareTo(a[i+1]) will result in a number < 0 if a[i] is < a[i+1] as for example if item a[i]
contained “Ant” and item a[i+1] contained “Dog”.
The reason for this is that the comparison is made using the ASCII numeric code for the
characters eg ‘A’ is 65 and ‘C’ is 67 and on comparison, 65 – 67 gives an answer of –2 which is
less than 0. Don’t worry about this but I’m just explaining why.
Claremont College 2015, based on Rosny College, 2009
Page 5 of 8
Other sort or ordering strategies for arrays
Insertion Sort - works on a sorted array. The item to be added to the list is inserted into the
appropriate place in the sorted list and all the items higher than the new item will move up one
place in the array.
Selection Sort - works on an unsorted array. If the array is to be sorted into ascending order,
then the largest item is found and moved to the last position in the array. The next largest item is
found and moved to the second last place etc.
Shuffle - There are times when you may need to make a sorted array in random order ie to
shuffle as in card games
// Shuffles an array into random order. From David Eck
public class shuffle extends Applet
{
int a[ ]={1, 5, 8, 56, 89, 99, 100};
//sorted array
int j, xpos, temp, randLoc;
public void paint(Graphics g)
{
//shuffle the array
for(int lastPlace = a.length-1; lastPlace > 0; lastPlace--)
{
// choose a random location (0 .. lastPlace)
randLoc = (int)(Math.random()*(lastPlace + 1));
temp = a[randLoc];
// swap items in locations randLoc and lastPlace
a[randLoc] = a[lastPlace];
a[lastPlace] = temp;
}
//output unsorted array
xpos=100;
g.drawString("Unsorted Array is ", 20, 80);
for(j = 0; j <= a.length-1; j++)
{
g.drawString(a[j] + "", xpos, 80);
xpos = xpos + 30;
}
}
} // end of shuffle
Claremont College 2015, based on Rosny College, 2009
Page 6 of 8
Two-dimensional arrays
A two-dimensional array is an array of arrays of a particular type.
An array of ints has the type int[] and an array of arrays of ints has the type int[][]. It is possible
to have 3 or more dimensional arrays but we will stick to 2-dimensional ones.
To declare a variable aa of type int[][] and to initialise it to refer to a newly created object use:
int[][] aa = new int[3][4];
where int[3][4] can be thought of as a grid of ints with 3 rows and 4 columns
If you create an array
aa = new int[3] [4],
you should think of it as a
"matrix' with 3 rows and
aa:
aa:
1 0
7
4 columns
(4)
12 -1
-3 2
5
-5 -2 2
9
1
(3)
0
12
Really, aa holds a reference to an array of 3 items,
where each item is a reference
-1
to an array of 4 ints.
(4)
Remember that arrays start with an index of 0,
so to refer to the fourth item in the third row use:
aa[2][3] which has the value 9.
Note:
 aa.length gives the number of rows of aa;
 aa[0].length gives the number of columns.
7
(4)
-3
-5
-2
2
2
5
9
A two-dimensional array can be created as a list of array initialisers, one for each row in the
array. The array aa shown on previous page can be created using:
int[][] aa = {
{1,0,12,-1},
{7,-3,2, 5},
{-5, -2,2,9}
};
Two-dimensional arrays can be used wherever data naturally falls into rows and columns:

grid on a chess board

students and test scores

monthly sales from a number of branches of a store.
Working with two-dimensional arrays
To process all the items in an array you need a for statement nested inside another.
Claremont College 2015, based on Rosny College, 2009
Page 7 of 8
Using the array aa with the following definition:
int[][] aa = new int[3][4]
you could store a 1 in each location of aa with the following code:
for (int row=0; row<3; row++)
{
for(int column=0; column<4; column++)
{
aa[row][column] = 1;
}
}
The first time the outer loop executes with row = 0, the inner for loop then fills in the four values
in the first row of aa. The outer loop executes with row = 1 and fills in the four values in the
second row of aa etc.
To add up all the items in an array eg tests of students
int
sum=0;
for (int student=0; student<3; student++)
for (int test=0; test<4; test++)
{
sum = sum + aa[student][test];
}
}
Claremont College 2015, based on Rosny College, 2009
Page 8 of 8
Download