Java Reference
In-Depth Information
public static String fixedWidth(long value, int width) {
char[] valChars = String.valueOf(value).toCharArray();
assert width> valChars.length;
char[] field = new char[width];
java.util.Arrays.fill(field, 0, width-valChars.length, ' '); // Partial fill
with spaces
for(int i = 0 ; i<valChars.length ; i++)
field[width-valChars.length+i] = valChars[i]; // Copy value characters
return new String(field);
}
Here we assemble the whole field as a character array. We fill the elements of the
field
array that will not
be occupied by characters for the value with spaces. We then copy the characters from the array
valChars
to the back of the field array. Finally we return a
String
object that we create from the field array.
Comparing Arrays
There are nine overloaded versions of the
equals()
method for comparing arrays, one for each of the
types that apply to the
fill()
method. All versions of
equals()
are of the form:
equals(
type
[] array1,
type
[] array2)
The method returns
true
if
array1
is equal to
array2
and
false
otherwise. The two arrays are
equal if they contain the same number of elements and the values of all corresponding elements in the
two arrays are equal. If
array1
and
array2
are both
null
, they are also considered to be equal.
When floating point arrays are compared,
0.0
is considered to be equal to
-0.0
, and two elements that
contain
NaN
are also considered to be equal. When arrays with elements of a class type are compared, the
elements are compared by calling the
equals()
method for the class. If you have not implemented the
equals()
method in your own classes then the version inherited from the
Object
class will be used. This
compares references, not objects, and so only returns
true
if both object references refer to the same object.
Here's how you can compare two arrays:
String[] numbers = {"one", "two", "three", "four" };
String[] values = {"one", "two", "three", "four" };
if(java.util.Arrays.equals(numbers, values))
System.out.println("The arrays are equal");
else
System.out.println("The arrays are not equal");
In this fragment both arrays are equal so the
equals()
method will return
true
.