Is there a way to make sure only a 3x3 array is passed into a method? I am trying to create a matrix class and a 3x3 matrix is a special case that can have the determine calculated, in terms of runtime, very quickly.
Printable View
Is there a way to make sure only a 3x3 array is passed into a method? I am trying to create a matrix class and a 3x3 matrix is a special case that can have the determine calculated, in terms of runtime, very quickly.
Yes. Arrays have a length property.
Code :
public class ArrayLengthEg { public static void main(String[] args) { int[] arr = new int[42]; System.out.println("Length is " + arr.length); } }
You could check that the array you are passed has length 3. You will also have to check that each element (which is also an array) also has length 3.
Sorry, I am going to make a math package, so I want to pass a 2d array and it can choose the fastest alforithm to use. The standard algorithm is very slow and matrix around 10x10 takes over a second. People who are building simulators that is not good for them. I want to make it as simple to use, so they don't have to search for the fastest they just call inverse() and pass a matrix through and have method overloading but with matrix size.
You can't overload methods based on the length of an array argument. Although an unchanging property of any given array, the length of an array is not part of its type.
Also although arrays can be interpreted as 2D matrices, Java arrays do not have a "dimension" in quite that way. A variable declared as double[][] is nothing but an array of double[] elements: that is, an array of arrays. These array elements can be interpreted as rows in which case the length property of the array argument will be the number of rows. Nothing, however, requires that these rows all have the same length. (or have any length at all - they may be null). In other words being a (square) 3x3 matrix is not something that is expressible as an array type. And because you can't express it as a type you can't use method overloading to distinguish between different inverse() methods.
What you can do is what I indicated before: have a single inverse() methods that looks at its array argument and responds appropriately. Where "appropriately" could be (a) calling a special case for small square matrices (b) calling some other method for larger matrices (c) throwing an IllegalArgumentException if it is not passed a square matrix at all.