Uploaded by ashten89006

Java Array Review

advertisement
Java Array Review
1-dimensional arrays
Array Terminology
● Contiguous memory space –arrays are stored such
that the elements are adjacent to one another on the
storage medium
Element 1
Element 2
Element 3
Element 4
● Elements are referenced by index, beginning at 0 and
ending at numberOfElements – 1
Creating arrays
● Declare an array reference
byte[] smallVals = new byte[10];
● Declare and initialize to default value
byte[] smallVals = new byte[10];
• Declare and initialize explicitly
byte[] smallVals = { 1, 3, 5, 7, 9, 11};
Array Terminology (cont.)
● An array reference is the variable that contains the
location (memory address) of the array.
double[] dArray = new double[4];
● “dArray is a reference to the array”
● “The array is referenced by dArray”
● Reference an element by its index—a set of brackets
with a whole number value following the reference
variable
dArray
Element 1
Element 2
Element 3
Element 4
index 0
index 1
index 2
index 3
dArray[0] is the first element in the array
● Each array has a property called “length” which
contains the number of elements in the array.
int numElements = dArray.length;
dArray[dArray.length – 1] is the last element
Types
● Arrays can contain only one type of data.
● Types can be
● Any primitive type: byte, short, int, long, float, double,
char, boolean
● Any defined class: Double, Car, String, Fruit, Location,
Account, Student, …
Typical uses for stored data
● Search the container for
● a key value
● duplicates
● Find minimum or maximum value
● Sum the contents
● Sort the contents
Download