February 28, 2021
Hot Topics:

The Essence of OOP using Java, Array Objects, Part 3

  • By Richard G. Baldwin
  • Send Email »
  • More Articles »

A reference to the array object at the root of the tree is stored in the reference variable of type Object named v3.  Note that the tree is designed to store references to objects of type String.

(The number of dimensions and the size of each dimension are specified by the reference to the array object of type int passed as the second parameter.)
Square-bracket cast is required here

The required type of the second parameter for this version of the newInstance method is int[].  Therefore, there was no way for me to avoid the use of square brackets.  I could either store the reference to the array object as type Object and cast it before passing it to the method, (which I did), or save it originally as type int[], (which I didn't).  Either way, I would have to know about the type int[].

Populate the leaf elements

The nested for loop in Listing 6 uses the various methods of the Array class to populate the elements in the leaf array objects with references to objects of the class String.

    for(int i=0;i<
      for(int j=0;j<
        Array.set(Array.get(v3,i), j, 
                    "b" + (i+1)*(j+1));
      }//end inner loop
    }//end outer loop

Listing 6

Admittedly, the code in Listing 6 is a little complex.  However, there is really nothing new there, so I won't discuss it further.

Display the data

Similarly, the code in Listing 7 uses the methods of the Array class in a nested for loop to get and display the contents of the String objects whose references are stored in the elements of the leaf array objects.  Again, there is nothing new here, so I won't discuss this code further.

    for(int i=0;i<Array.getLength(v3);
      for(int j=0;j<Array.getLength(
            Array.get(v3,i), j) + " ");
      }//end inner loop
    }//end outer loop

Listing 7

Very few square brackets

I will point out that with the exception of the requirement to create and pass an array object as type int[], it was possible to write this entire example without the use of square brackets.  This further illustrates the fact that the Array class makes it possible to create and work with array objects in a method-oriented manner, almost devoid of the use of square-bracket notation.

Sorting and Searching

Many college professors require their students to spend large amounts of time reinventing algorithms for sorting and searching (and for various collections and data structures as well).  There was probably a time in history when that was an appropriate use of a student's time.  However, in my opinion, that time has passed.

Reuse, don't reinvent

Through a combination of the Arrays class, and the Java Collections Framework, most of the sorting, searching, data structures, and collection needs that you might have are readily available without a requirement for you to reinvent them.  (One of the most important concepts in OOP is reuse, don't reinvent.)

I will now illustrate sorting and searching using static methods of the Arrays class.

(Note that the Arrays class is different from the Array class discussed earlier.)
Create, populate, and display an array object

To give us something to work with, Listing 8 creates, populates, and displays the contents of an array object.  Note that the array object is populated with references to String objects.  There is nothing new here, so I won't discuss the code in Listing 8 in detail.

    Object v4 = Array.newInstance(
               "java.lang.String"), 8);
    //Populate the array object.
    // Create a gap in the data.
    for(int i = 0; i < 
             Array.getLength(v4); i++){
      if(i<4){Array.set(v4, i, 
      else{Array.set(v4, i,
    }//end for loop
    //Display the raw data
    for(int i = 0; i < 
             Array.getLength(v4); i++){
      System.out.print(Array.get(v4, i)
                                + " ");
    }//end for loop

Listing 8

The output

The code in Listing 8 produces the following output on the screen:

c8 c7 c6 c5 c14 c13 c12 c11

Note that the order of this data is generally descending, and there is no string encapsulating the characters c4.

Sort and display the data

The code in Listing 9 uses the sort method of the Arrays class to sort the array data into ascending order.

    //Display the sorted data
    for(int i = 0; i < 
             Array.getLength(v4); i++){
               Array.get(v4, i) + " ");
    }//end for loop

Listing 9

The output

The code in Listing 9 displays the sorted contents of the array object, producing the following output on the computer screen:

c11 c12 c13 c14 c5 c6 c7 c8

Note that the order of the data in the array object has been modified, and the array data is now in ascending order.

(This order is based on the natural ordering of the String data.  I discuss other ways to order sorted data in conjunction with the Comparable and Comparator interfaces in my lessons on the Java Collections Framework.)
Binary search

A binary search is a search algorithm that can very quickly find an item stored in a sorted collection of items.  In this case, the collection of items is stored in an array object, and the data is sorted in ascending order.

Search for an existing string

Listing 10 uses the binarySearch method of the Arrays class to perform a search for an existing String object whose reference is stored in the sorted array.  The code searches for the reference to the String object encapsulating the characters c5.


Listing 10

The result of the search

The code in Listing 10 displays the numeral 4 on the screen.  When the binarySearch method finds a match, it returns the index value of the matching element.  If you go back and look at the sorted contents of the array shown earlier, you will see that this is the index of the element containing a reference to a String object that encapsulates the characters c5.

Search for a non-existing string

The code in Listing 11 uses the binarySearch method to search for a reference to a String object that encapsulates the characters c4.  As I indicated earlier, a String object that encapsulates these characters is not represented in the sorted array object.


Listing 11

The result of the search

The code in Listing 11 produces the following negative numeral on the screen:  -5.  Here is Sun's explanation for the value returned by the binarySearch method:

"Returns:  index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size(), if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found."
Thus, the negative return value indicates that the method didn't find a match.  The absolute value of the return value can be used to determine the index of the reference to the target object if it did exist in the sorted list.  I will leave it as an exercise for the student to interpret Sun's explanation beyond this simple explanation.

Other capabilities

In addition to sorting and searching, the Arrays class provides several other methods that can be used to manipulate the contents of array objects in Java.

Page 3 of 4

This article was originally published on July 9, 2002

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date