Java Reference
In-Depth Information
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 elements that con-
tain
NaN
are also considered to be equal. Array elements of a class type are compared by calling their
equals()
method. If you have not implemented the
equals()
method in your own classes, then the version
inherited from the
Object
class is used. This compares references, not objects, and so returns
true
only if
both 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 returns
true
.
Sorting Arrays
The static
sort()
method in the
Arrays
class sorts the elements of an array that you pass as the argument
into ascending sequence. The method is overloaded for eight of the nine types (
boolean
is excluded) you
saw for the
fill()
method, for each of two versions of
sort()
:
void sort(
type
[] array)
void sort(
type
[] array, int fromIndex, int toIndex)
The first variety sorts the entire array into ascending sequence. The second sorts the elements from
ar-
ray[fromIndex]
to
array[toIndex-1]
into ascending sequence. This throws an
IllegalArgumentEx-
ception
if
fromIndex
is greater than
toIndex
. It throws an
ArrayIndexOutOfBoundsException
if
fromIndex
is negative or
toIndex
is greater than
array.length
.
You can pass an array of elements of any class type to the versions of the
sort()
method that have the
first parameter as type
Object[]
. If you are using either variety of the
sort()
method to sort an array of
objects, then the objects must support the
Comparable<>
interface because the
sort()
method uses the
com-
pareTo()
method.
Here's how you can sort an array of strings:
String[] numbers = {"one", "two", "three", "four", "five",
"six", "seven", "eight"};
java.util.Arrays.sort(numbers);
After executing these statements, the elements of the
numbers
array contain: