Home : Course Map : Chapter 10 : Java :
The Arrays Class
Course Map
Chapter 10


Preferences API
  Demo 1
Concurrency Utils
Enumerated Type
Arrays Class
String Tools

  Demo 2
  Demo 3

Other Utilities

     About JavaTech
     Codes List
     Topic Index
     Course Guide
     What's New

The class java.util.Arrays provides a number of static methods for filling, searching, sorting, and comparing arrays. For each method name, there are several overloaded versions that differ according to the type of the array or array arguments. We examine several of these in more detail here.


Let's consider the equals() method (actually methods, since there are several overloaded versions). There is one for each primitive type plus one more for Object arrays:

boolean equals (type[] array1, type[] array2)

These compare two input arrays of the same type for equality. The methods return true if each array holds the same number of elements and each element in array1 equals the value in the corresponding element in array2. For the case of Object arrays, the references in the two corresponding elements must either point to the same object or both equal null.


There are two forms of the fill() methods:

void fill (type[] array, type value)
void fill (type[] array, int fromIndex, int toIndex, type value)

The first version of the overloaded fill methods, one for each primitive type and for Object, fill all elements in array of the same type with the value argument. The second version fills those elements between the given indices.


In Chapter 8: Tech : Histogram Sorting we discussed the sort methods in Arrays and used them in demonstration program that sorted histogram bins. So here we will just briefly review the basics.

The sort methods for the primitive types look like:

void sort (type[] array)
void sort (type[] array, int fromIndex, int toIndex)

There is a sort method for each primitive type except boolean. The elements in the array are sorted in ascending order using a variant of the QuickSort algorithm. (See the Java 2 API Specifications for the java.util.Arrays class for details of the algorithm.) The second version sorts those elements between the given indices.

For sorting Object types, there are two approaches. For the first approach there are two methods available:

void sort (Object[] array)
void sort (Object[] array, int fromIndex, int toIndex)

Here the objects are sorted into ascending order using the "natural ordering" of the elements. The array elements must implement the java.lang.Comparable interface and provide the method

int compareTo (Object)

This method defines the "natural ordering" such that comparing object x to y results in a negative number if x is lower than y (on a scale that makes sense for the class), equal to 0 if the objects are identical, and a positive number if x is greater than y.

Your compareTo() method must be written to return a negative, zero, or positive integer according to the ordering rules that make sense for the nature of the objects that the class describes.

For example,

MyClass my_class1 = someMethodThatBuildsAMyClassInstance ();
MyClass my_class2 = someMethodThatBuildsADifferentMyClassInstance ();

// Now compare the two instances of MyClass
if (my_class1.compareTo (my_class2) < 0)
    System.out.println ("my_class1 is 'less than' my_class2");
else if (my_class1.compareTo (my_class2) == 0)
    System.out.println ("my_class1 is 'equal to' my_class2");
    System.out.println ("my_class1 is 'greater than' my_class2");

For the alternative approach to comparing Object arrays, you create an auxiliary class that implements the java.util.Comparator interface and that knows how to compare and order two objects of interest. This technique is particularly useful if you need to sort classes that you cannot re-write to implement the Comparable interface. The Comparator class has two methods

int compare (Object obj1, Object obj2)
boolean equals (Object obj1, Object obj2)

The compare() method should return a negative, zero, or positive integer, according to the ordering rules that you implement, if obj1 is less than, equal to, or greater than obj2. Similarly, the equals() method compares the objects for equality according to the rules you implement. When using the Comparator technique, the two object array sorting methods are:

void sort (Object[] array, Comparator comp)
void sort (Object[] array, int fromIndex, int toIndex, Comparator comp)


Another useful set of overloaded methods in the Arrays class is the set of binary searching methods:

int binarySearch (type[] array, type key)
int binarySearch (Object[] array, Object key, Comparator comp)

There is an overloaded binarySearch() method for each primitive type except boolean and one more for Object. These methods search an array for the given key value. The array to be searched must be sorted first in ascending order, perhaps by using one of the sort() methods just discussed.

The methods return the index to the position where the key is found, or if it is not found, to the insertion point. The insertion point is the place in the array where all the elements are less than the key and all the elements above it are greater than or equal to it. The methods return array.length() if all elements are less than the key.

For the case of Object arrays and the first type of binarySearch() method above, the elements must implement the Comparable interface. If you cannot change the classes to implement this interface, then you can provide a Comparator and use the second type of binarySearch() method shown above.


One small, but extremely useful, addition to J2SE 5.0 is the static Arrays.toString() method. It conveniently returns a string representation of the contents of an array. Consider the now familiar public static void main (String[] args) method. Most anyone who has used Java for any time has written a loop like the following to echo the input parameters

for (int i=0; i < args.length; i++)
    System.out.println (args[i] + ", ");

Wouldn't it be nice to avoid rewriting that loop ever again? Arrays.toString() provides just what you need. It accepts an array as a parameter and returns a formatted string representation of the contents of the array. There are overloaded versions for arrays of all the primitive types and a version for object types.

For the object types, each element's own toString() is used. Therefore for String[] types, you get the contents of the string. Here is a simple example.

public class Demo {
  public static void main (String[] args) {
    System.out.println (Arrays.toString (args));
} // class Demo

If you run this code with the following command-line parameters

c:\> java Demo Arrays.toString is really cool

you are greeted with

[Arrays.toString, is, really, cool]

Arrays.deepToString()and deepEquals()

There is also a recursive Arrays.deepToString() that works as might be expected for multidimensional arrays. This code snippet

int[][] a = new int[3][4];
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[0][3] = 4;

a[1][0] = 5;
a[1][1] = 6;
a[1][2] = 7;
a[1][3] = 8;

a[2][0] = 9;
a[2][1] = 10;
a[2][2] = 11;
a[2][3] = 12;

System.out.println (Arrays.deepToString (a));


[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

Finally, for comparing multidimensional arrays, there is the deepEquals() method. It returns a boolean and works recursively on nested arrays of any depth. Two array references are considered deeply equal if they contain the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal. (If both array references are null they are also considered deeply equal.)

References and Web Resources


Latest update: Nov. 18, 2004

Bit Handling

Data Gen&Analysis

  Demo 1
  Demo 2

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
22 23 24

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.