0% found this document useful (0 votes)
4 views

Unit_4_-_Arrays

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit_4_-_Arrays

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Arrays

FACULTY OF COMPUTER SCIENCE


UNIVERSITAS INDONESIA

What is an Array?

 It is often convenient to be able to group a series of data together and


be able to refer to individual data items whenever necessary.
 An array has a name which follows the normal variable naming
conventions of the programming language concerned.
 Each data item in an array is called an array element.
 Each data item in an array is referred to by an integer value which
denotes the data items position in the array. This integer value is called
an array subscript.
 The data values in an array are characterised by:
 having the same name
 being all the same type
 being individually specified via the subscript
 being thought of as in subscript order

 2005 Pearson Education, Inc. All rights reserved.

1
The size of an array is fixed

 The size of an array is defined by the maximum


number of elements which can be stored in it.
 Once the size of an array has been set it cannot be
changed.
 Some languages force the setting of array sizes to be
done at compile time.
 Other languages (e.g. Java) all array sizes to be set at
run time.
 In either case the number of data elements stored in an
array may vary from one part of an algorithm to the
next.
 Strategy is to set the array to the maximum required
size and then use only the portion required.
 This means the size of an array is described by its
actual size and also the number of elements currently
used.

 2005 Pearson Education, Inc. All rights reserved.

Arrays as method parameters

 Typically when passing an array as a parameter to a


method/function /subroutine/procedure, the actual
information that is passed is the memory address of
the first element.
 This means that any modification to an array’s
elements within the method will be reflected back in
the calling module
 This also means that some languages require the
number of elements and possibly the maximum size
to be parameters to the method.
 This is not required in Java.

 2005 Pearson Education, Inc. All rights reserved.

2
Arrays Subscripts

 In Java, array elements are always subscripted from zero.


 When specifying an array element, we are actually describing
how to calculate the memory address of the array element.
 The address of the first element in the array is known as the
base address.
 The memory location of a particular element is calculated by:
 multiplying the subscript value by the size of each element.
 adding this value to the base address
 In order for this to work correctly then for the first element in
the array the offset from the base address must be zero.
 This is achieved by subscripting from zero.

 2005 Pearson Education, Inc. All rights reserved.

Arrays in Java

 Arrays in Java are represented as objects.


 This means that each array has to be constructed
before it can be used.
 Although technically arrays are objects in Java,
their implementation is not exactly the same as
with other objects and classes and the
documentation on arrays is almost non−existent.

 2005 Pearson Education, Inc. All rights reserved.

3
Declaring Arrays

 Declaring arrays is similar to declaring ordinary


variables except that a set of open and close square
brackets (i.e. []) is added for each dimension.
 Examples:
int numlist[];
double matrix[][];
double minepit[][][];

 2005 Pearson Education, Inc. All rights reserved.

Constructing Arrays

 The constructors for arrays look a bit different to


normal constructors
 The syntax is:
arrayVariable = new datatype[size];
 Examples
numlist = new int [maxSize];
matrix = new double [maxRow][maxCol];
minepit = new double [maxPlane][maxRow][maxCol];
 We can create arrays of objects too
String b[] = new String[ 100 ];

 2005 Pearson Education, Inc. All rights reserved.

4
The length variable for 1D Arrays

 Arrays have a public variable called length which is


set to the length of the array.
 Example:
public static void main( String args[])
{
double numbers[] = new double [50];
System.out.println("Array has " +
numbers.length + " elements");
}

 2005 Pearson Education, Inc. All rights reserved.

The length variable for 2D Arrays

 A 2D array can be thought of as a series of 1D arrays. i.e.


each row is a 1D array.
 This is how multi dimensional arrays are implemented in
Java.
 Given a 2D array: double array2D[][];
 Referring to array2D[row] is referring to the 1D array that
is used for that row.
 This means that:
 array2D.length is the number of rows in the array.

 array2D[r].length is the number of columns in row r.

 2005 Pearson Education, Inc. All rights reserved.

5
Example

import io.*;
public class arrayTest
{
public static void main( String args[])
{
int x[], y[][], z[][][];
x = new int[10];
y = new int[5][5];
z = new int[3][3][3];
System.out.println("x has " + x.length + " elements");
System.out.println("y has " + y.length + " rows ");
System.out.println("y has "+y[0].length + " columns
");
System.out.println("z has " + z.length + " planes");
System.out.println("z has " + z[0].length + " rows ");
System.out.println(
"z has " + z[0][0].length + " columns ");
}
}

 2005 Pearson Education, Inc. All rights reserved.

Ragged Two−Dimensional Arrays

 A ragged 2D array is one where the number of


columns in each row is different.

 A way of minimising memory usage by only


allocating memory for what is required.
 Not needed very often but can be useful.

 2005 Pearson Education, Inc. All rights reserved.

6
Example

public static void main( String [] args)


{
int ragged [][];
ragged = new int [10][];
for(int row=0; row<10; row++)
ragged[row] = new int [row+2];
for(int row =0; row<10; row++)
for(int col=0; col<row+2;col++)
ragged[row][col] = row*col;
System.out.println("arrays has " +
ragged.length + " rows");
for(int row =0; row<10; row++)
System.out.println("row " + row + " has
“ + ragged[row].length + " columns");
}

 2005 Pearson Education, Inc. All rights reserved.

Passing arrays into and out of methods

 An array in Java is an object. This means that what is


stored in the array variable is the memory location of
the array.
 Methods can return references to arrays.
 Arrays are passed into methods by passing in their
memory location.
 If an array is passed as an argument to a method and
its contents altered inside the method then this change
will be reflected in the calling module.
 The example on the next slide illustrates the concepts.

 2005 Pearson Education, Inc. All rights reserved.

7
Example

import io.*;
public class raggedeg2
{
public static void main( String [] args)
{
int ragged [][];
ragged = createArray(10);
fillArray( ragged);
outputArraySize( ragged);
}

 2005 Pearson Education, Inc. All rights reserved.

private static int [][] createArray(int


numRows)
{
int array[][];
array = new int [numRows][];
for(int row=0; row<10; row++)
array[row] = new int [row+2];
return array;
}
 Question: Why does the method have to return the
array reference?

 2005 Pearson Education, Inc. All rights reserved.

8
private static void fillArray( int array[][])
{
for(int row =0; row<10; row++)
for(int col=0; col<row+2;col++)
array[row][col] = row*col;
}
private static void outputArraySize( int [][] array)
{
System.out.println("arrays has " + array.length + "
rows");
for(int row =0; row<10; row++)
System.out.println("row " + row + " has “ +
array[row].length + " columns");
}
}

 2005 Pearson Education, Inc. All rights reserved.

Array Initializer
18

 Using an array initializer


 Use initializer list
Items enclosed in braces ({})
Items in list separated by commas
int n[] = { 10, 20, 30, 40, 50 };
Creates a five-element array

Index values of 0, 1, 2, 3, 4

 Do not need keyword new

 2005 Pearson Education, Inc. All rights reserved.

9
Exercise
19

 Write a method that creates, initializes, and


returns an array of type double . The method
will have 3 arguments: the size of the
array, the starting value, and the ending
value. Initialize each value in the array to
use the specified range.
 Write a second method that accepts a double []
and prints it.
 Exercise the methods from main.

 2005 Pearson Education, Inc. All rights reserved.

 Split the previous into 2 classes, one of which


has the main method, the other of which has all
the others
 In the non-main class, have everything NOT
static
 Have the main method instantiate the other
class and exercise its methods using the object
reference

 2005 Pearson Education, Inc. All rights reserved.

10
Enhanced for Statement
21

 Enhanced for statement


 New feature of J2SE 5.0
 Allows iterates through elements of an array or a
collection without using a counter
 Syntax

for ( parameter : arrayName )


statement

 2005 Pearson Education, Inc. All rights reserved.

1 // Fig. 7.12: EnhancedForTest.java


2
3
// Using enhanced for statement to total integers in an array. Outline
22

4 public class EnhancedForTest


5 {
6 public static void main( String args[] )
 EnhancedFo
7 {
rTest.java
8 int array[] = { 87, 68, 94, 100 , 83, 78, 85, 91, 76, 87 };
9 int total = 0;
For each iteration, assign the next
10
11 // add each element's value to total
element of array to int variable
12 for ( int number : array ) number, then add it to total
13 total += number;
14
15 System.out.printf( "Total of array elements : %d \n", total );
16 } // end main
17 } // end class EnhancedForTest

Total of array elements: 849

11
Enhanced for Statement (Cont.)
23

 Lines 12-13 are equivalent to


for ( int counter = 0; counter < array.length;
counter++ )
total += array[ counter ];

 Usage
 Canaccess array elements
 Cannot modify array elements

 Cannot access the counter indicating the index

 2005 Pearson Education, Inc. All rights reserved.

Variable-Length Argument Lists


24

 Variable-length argument lists


 New feature in J2SE 5.0
 Unspecified number of arguments

 Use ellipsis (…) in method’s parameter list

Can occur only once in parameter list


Must be placed at the end of parameter list
 Array whose elements are all of the same type

 2005 Pearson Education, Inc. All rights reserved.

12
1 // Fig. 7.20: VarargsTest.java
2
3
// Using variable-length argument lists.
Outline
25
4 public class VarargsTest
5 {
6 // calculate average
7 public static double average( double... numbers )
 VarargsTest
8 {
 .java
 (1 of 2)
9 double total = 0.0; // initialize total  Line 7
 Lines 12-13
10  Line 15
11 Method
// calculate total using the enhanced average receives a variable
for statement
12 for ( double d : numbers ) length sequence of doubles
13 total += d;
14
15 return total / numbers.length;
Calculate
the total of the
16 } // end method average
doubles in the array
17
18 public static void main( String args[] )
19 {
Access numbers.length to obtain
20 double d1 = 10.0; the size of the numbers array
21 double d2 = 20.0;
22 double d3 = 30.0;
23 double d4 = 40.0;
24

25 System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n",


26
27
d1, d2, d3, d4 ); Outline
26

28 System.out.printf( "Average of d1 and d2 is %.1f\n",


29 average( d1, d2 ) );
Invoke method average with
30 System.out.printf( "Average of d1, d2 and d3 is %.1f\n",  VarargsTest
31 average( d1, d2, d3 ) );
two arguments  .java
 (2 of 2)
32 System.out.printf( "Average of d1, d2, d3 and d4 is %.1f\n", 

Line 29
Line 31
 Line 33
33 average( d1, d2, d3, d4 ) );  Program output

34 } // end main Invoke method average with


35 } // end class VarargsTest three arguments
d1 = 10.0
d2 = 20.0
d3 = 30.0
d4 = 40.0
Average of d1 and d2 is 15.0
Average of d1, d2 and d3 is 20.0
Average of d1, d2, d3 and d4 is 25.0 Invoke method average with
four arguments

13
Using command-line Arguments

 Command-line arguments
 Pass arguments from the command line
 String args[]
 Appear after the class name in the java command
 java MyClass a b
 Number of arguments passed in from command line
 args.length

 First command-line argument


 args[ 0 ]

1 // Fig. 7.21: InitArray.java


2
3
// Using command-line arguments to initialize an array. 28
Outline
4 public class InitArray
5 {
6 public static void main( String args[] )
 InitArray
7
8
{
// check number of command-line arguments
.java
 (1 of 2)
9 if ( args.length != 3 )
10 System.out.println(
Array args stores command-  Line 6
linecommand,
arguments  Line 9
11 "Error: Please re-enter the entire including\n" +
 Line 16
12 "an array size, initial value and increment." );
Check number of arguments  Lines 20-21
13 else
passed in from the command line  Lines 24-25
14 {
15 // get array size from first command-line argument
16 int arrayLength = Integer.parseInt( args[ 0 ] );
17 int array[] = new int[ arrayLength ]; // create array
18
19 // get initial value and increment from command-line
Obtain firstargument
command-line argument
20 int initialValue = Integer.parseInt( args[ 1 ] );
21 int increment = Integer.parseInt( args[ 2 ] );
22
23 // calculate value for each array element
24 for ( int counter = 0; counter < array.length; Obtain second
counter++ ) and third
25 array[ counter ] = initialValue + incrementcommand-line
* counter; arguments
26
27 System.out.printf( "%s%8s\n", "Index", "Value" );
28 Calculate the value for each array element
based on command-line arguments

14
29 // display array index and value
29
30
31
for ( int counter = 0; counter < array.length; counter++ )
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
Outline
32 } // end else
33 } // end main
34 } // end class InitArray

java InitArray  InitArray


Error: Please re-enter the entire command, including
an array size, initial value and increment. .java
 (2 of 2)
Missing
java InitArray 5 0 command-line
4 arguments  Program output
Index Value
0 0
1 4
2 8
3 12 Three command-line arguments are
4 16
5, 0 and 4

java InitArray 10 1 2
Index Value
0 1
1 3
2 5
3 7 Three command-line arguments are
4 9
5 11 10, 1 and 2
6 13
7 15
8 17
9 19

java.utils.Arrays
30

 There are four basic functions:


 equals( ), to compare two arrays for equality
 fill( ), to fill an array with a value
 sort( ), to sort the array
 binarySearch( ), to find an element in a sorted array

 All of these methods are overloaded for all the


primitive types and Objects
 In addition, there’s a single asList( ) method that
takes any array and turns it into a List container

15
 To be equal, the arrays must have the same
number of elements and each corresponding
element must be equivalent, using the equals( )
for each element
 For primitives, that primitive’s wrapper class equals( )
is used
 such as Integer.equals()

16

You might also like