|
|
||
| You are here: | ||
|
Parallel arrays often come up in the examination. An altyernative data structure would be an array of records.
using arrays as method parameters - an SL mastery aspect
|
Consider two arrays, scores and names:
Record structures are discussed further elswhere . Worked example Given an array scores and another array pass Write the function that examines scores and assigns the value true or false to the corresponding element of pass when the score is over 50:
The value in scores[0] is examined. It is <= 50 so the value false is assigned to pass[0]. A simple method to do this is shown below: private void allocate( int scores[], bool pass[], int size ) This illustrates some interesting points: 1. Objects and Primitives as Parameters Primitives, by comparison are passed-by-value . Therefore a primitive (eg size) is not altered in the calling routine. For example if the line: allocate( scores[], pass[], size ); is used to call allocate, scores and pass could change but size cannot, even if a line like: size = size - 1; is placed in the allocate method. Incidentally, if you do need to pass primitives by reference ( not a recommended practice but sometimes neccessary) you can use the Java wrapper classes (Integer, Double, Boolean, etc). 2. Assigning boolean expressions to boolean primitives boolean check = ( (x < y) && (z > m) ); is a perfectly valid statement. 3. The "off-by-one" error void allocate( int scores[], bool pass[], int size ) The pointer ( i ) used to access the array continues until it is equal to size . Unfortunately, since Java arrays are 0-based (their first element is 0), the array has elements only 0 to ( size - 1 ). Such an error can have serious consequences in other languages (such as C++) but are caught by Java when the application runs. Related: [ Java home | Previous: More 2D arrays ] |
|
|
|
|||
|
Questions or problems related to this web site should be addressed to Richard Jones who asserts his right to be identified as the author and owner of these materials - unless otherwise indicated. Please feel free to use the material presented here and to create links to it for non-commercial purposes; an acknowledgement of the source is required by the Creative Commons licence. Use of materials from this site is conditional upon your having read the additional terms of use on the about page and the Creative Commons Licence. View privacy policy. This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. © 2001 - 2009 Richard Jones, PO BOX 246, Cambridge, New Zealand; This page was last modified: May 31, 2009 |