Java Reference
In-Depth Information
and if the element exceeds the declared length of the array, an out of bounds
run-time exception is thrown.
Thus, unlike in C or C
,aprogram cannot run off the end of an array
and write to places in memory where it should not. This avoids a very common
program bug and source of security attacks that can be difficult to track down
since the problem may not show up until well after the write occurs. On the other
hand, there is some performance penalty in the bounds checking that can show
up when doing intensive processing with arrays.
++
4.7.5 Mathematical vectors and matrices
Vector and matrix operations are obviously standard tools throughout science and
engineering. Here we look at some ways to use Java arrays to represent and carry
out operations for vectors and matrices.
Note that the Java core language includes a class called Vector in the
java.util package (see Chapter 10). Vector is similar to the ArrayList
discussed above (see Section 4.6.3); both provide a dynamic list that allows for
both adding and removing elements. ArrayList and Vector are often quite
useful, but they are slow and not intended for mathematical operations.
4.7.5.1 Mathematical vectors
The elements of a floating-point array can represent the component values of a
vector, as in
double[] vec1 ={ 0.5,0.5,0.5 } ;
double[] vec2 ={1.0,0.0,0.2 } ;
We then need methods to carry out various vector operations such as the dot
product:
double dot (double[] a, double[] b) {
double dot - prod = 0.0;
for (int i=0; i < a.length; i++) {
dot - prod += a[i]*b[i];
}
return dot - prod;
}
Note that a more robust method would check that the vector arguments are not
null and that the array lengths are equal.
Several numerical libraries are available that provide classes with methods to
carry out vector operations. The Web Course Chapter 4 provides links to several
of these.
Search WWH ::




Custom Search