Arrays
- list of values containing the same data type
0 based
C++ has static and dynamic arrays
- Java treats its arrays like objects. You delcare a reference, meaning no size can be specified until specified.
Using Arrays
- has length attribute
Bounds Checking
- Java does automatic run time bounds checking for all array index operations
- C/C++ can't do that because it will sef gault
- Downside? Efficiency suffers, checking every sincel array index a run-time takes a while
Assigning Array References
- Assigning one reference to another results in both references referring to the same object
- Arrays are NOT an ecepton
Cloning an Array
- If you want an array ference to refer to an array object that is a copy of another array obeject, can use clone
- Cloning causes a new object
Int is a generic function that can be used on any objec, therfore, its return value msut be cast
To copy elements fo an array into an array object that has already been allocated:
- Use a for loop or
- Use System.arrayCopy(
, );
int [] squareVals;
int [] arrayRef;
int [] anotherCopy;
// Don't have to allocate memory, clone automatically creates new memory
arrayRef = (int [])squareVals.clone();
// arraycopy requires memoy to be already allocated.
anotherCopy = new int[5];
System.arraycopy(squareVals, 0, anotherCopy, 0, 5);
Arrays of Objects
- No such thing in Java there are only arrays of object references.
- Even when you use new to allocate space for an array object, you have to only allocated object references
- You must use new on each array element to actually allocate an object
Multidimensional Arrays
- No such thing in Java
- To use a 2d array, you use a 1D array where each element refers to a 1D array. Each individual 1d array can be a different size
- Allocate mutli-dimensional arrays
twoDAry = new int[10][60]; - One dimension at a time, starting with the left more dimension first
twoDAry = new int[10][]; for(int i = 0; i < toDAry.length; i) { twoDAry[i] = new int[60]; }