I have a Rational number class with a construtor with a default value of 0/1 called like this:
public Rational (){ this(0, 1);}
public Rational (int numerator, int denominator){
this.numerator = numerator;
if (denominator== 0)
throw new IllegalArgumentException("Denominator can't be zero.");
this.denominator = denominator;
}
Now, in a subclass, I want to create an array of Rationals. They come all set to "null". So I have two methods inside the Rational class that set all values to zero. I have one for a simple array and another for a matrix:
public Rational[] zero(Rational[] array){
for (int i=0; i<array.length; i++)
array[i] = new Rational();
return array;
}
public Rational[][] zero (Rational[][] matrix){
for (int i=0; i<matrix.length; i++)
for(int j=0; j<matrix[i].length; j++)
matrix[i][j] = new Rational();
return matrix;
}
First, would it be better to used improved loops? Something like:
public Racional[][] zero(Racional[][] matrix){
for (Racional[] arr : matrix)
for (Racional rat : arr)
rat = new Rational();
return matrix;
}
Second, is there a way to create an array or matrix without having to manually zero all the positions as we can do with primitive types.
e.g.:
int[] arr = new int [10]; //All zero
Rational[] arr = new Rational [10]; //All null
arr = arr.zero (arr); //All "default" - 0/1
Arrays.fill.Arrays.fill()works for objects also, but it is applicable here only ifRationalis immutable.