Java Reference
In-Depth Information
boolean
byte
char
float
double
short
int
long
Object
The version of
fill()
accepting an array argument of type
Object[]
will obviously process an array
of any class type.
Here's how you could fill an array of integers with a particular value:
long[] values = new long[1000];
java.util.Arrays.fill(values, 888L); // Every element as 888
It's a relatively common requirement to fill an array of type
char[]
with spaces. Here's how you might
use the
fill()
method in a method to put a value in a fixed width field:
// Return a value right justified in a field
public static String fixedWidth(double value, int width) {
String valStr = String.valueOf(value);
assert width> valStr.length();
char[] spaces = new char[width-valStr.length()];
java.util.Arrays.fill(spaces, ' '); // Fill array with blanks
return new StringBuffer().append(spaces).append(valStr).toString();
}
This converts the value passed as the first argument to a string and checks that the field width specified
is greater than the length of this string. The assertion ensures that we don't attempt to create an array
with a negative number of elements. We then create an array of type
char[]
that will provide the
spaces to the left of the value string. We fill this using the
fill()
method from the
Arrays
class in the
java.util
package. We then assemble the field as a
StringBuffer
object by appending the array
followed by the value string and convert the result to type
String
before returning it. Clearly you
could easily create an overloaded version of this method to output values of any basic type in a fixed
width field. You could even embellish it with an option for left or right justification in the field.
There is a further form of
fill()
method that accepts four arguments. This is of the form:
fill(
type
[] array, int fromIndex, int toIndex,
type
value)
This will fill part of
array
with
value
, starting at
array[fromIndex]
up to and including
array[toIndex-1]
. There are versions of this method for the same range of types at the previous set
of
fill()
methods. This variety of
fill()
will throw an exception of type
IllegalArgumentException
if
fromIndex
is greater than
toIndex
. It will also throw an
exception of type
ArrayIndexOutOfBoundsException
if
fromIndex
is negative or
toIndex
is
greater than
array.length
.
We could have taken a different approach to the
fixedWidth()
method and used this version of
fill()
in the process: