December 21, 2014
Hot Topics:

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

  • July 9, 2002
  • By Richard G. Baldwin
  • Send Email »
  • More Articles »

Summary

This lesson is the third in a series of lessons that discuss various aspects of array objects in Java.

An array object has the following members (in addition to the data stored in the object):

  • A public final variable named length
  • An overridden version of the public method named clone
  • Default versions of all the other methods inherited from the class named Object
Every array object implements the Cloneable and Serializable interfaces.

A clone of a multidimensional array is shallow.  Therefore, you should exercise caution when cloning array objects.

Because array objects implement the Serializable interface, they can be serialized and later reconstructed.

Every array also has an associated Class object.

The classes named Array and Arrays provide methods that you can use to work with array objects.

The Array class provides static methods to dynamically create and access Java array objects.

The Arrays class contains various methods for manipulating arrays (such as sorting and searching). It also contains a static factory method that allows arrays to be viewed as lists.

Class objects are required when using the methods of the Array class to dynamically create Java array objects.

There are nine predefined Class objects that represent the eight primitive types and void. They are accessed using the following syntax: boolean.class, int.class, etc.

Three ways to get a Class object are:

  • Class objects for primitive types: int.class, etc.
  • The getClass method
  • The forName method
The methods of the Array class make it possible to deal with one-dimensional array objects using a syntax that is completely devoid of square brackets.  This is a method-oriented approach to the use of array objects.  This makes it possible to treat array objects much the same as we treat ordinary objects in Java. The required syntax for multi-dimensional array objects is mostly devoid of square brackets.

The Arrays class provides methods for sorting and searching array objects as well as performing other operations on array objects as well.

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.

What's Next?

The next lesson in this miniseries will explain the use of the this and super keywords.

Complete Program Listing

A complete listing of the program is shown in Listing 12 below.
 
/*File Array08.java
Copyright 2002, R.G.Baldwin
Rev 2/10/02

This program illustrates the use of 
static methods of the Array class to 
dynamically create and access Java
arrays.

It also illustrates the use of static
methods of the Arrays class to sort
and search array objects. 

Tested using JDK 1.3 under Win 2000.
**************************************/
import java.lang.reflect.Array;
import java.util.Arrays;

public class Array08{
  public static void main(
                        String[] args){
  
  try{
    //Create, populate, and display a
    // one-dimensional array object
    // whose elements contain 
    // references to objects of type 
    // String.
    
    //Create the array object
    Object v1 = Array.newInstance(
              Class.forName(
               "java.lang.String"), 3);
    //Populate the array object
    for(int i = 0; i < 
             Array.getLength(v1); i++){
      Array.set(v1, i, "a"+i);
    }//end for loop
    //Display the data
    for(int i = 0; i < 
             Array.getLength(v1); i++){
      System.out.print(
               Array.get(v1, i) + " ");
    }//end for loop
    System.out.println();
    System.out.println();
    
    //Create, populate, and display a
    // rectangular two-dimensional
    // array object tree whose 
    // elements contain references
    // to objects of type String.
    
    //First create an array object of
    // type int required as a 
    // parameter to the newInstance
    // method.  Populate it to later
    // specify a rectangular array
    // object tree with two rows and
    // three columns.
    Object v2 = Array.newInstance(
                         int.class, 2);
    Array.setInt(v2, 0, 2);
    Array.setInt(v2, 1, 3);
    //Now create the actual two-
    // dimensional array object tree.
    Object v3 = Array.newInstance(
       Class.forName(
       "java.lang.String"), (int[])v2);

    //Populate the leaf elements with
    // references to objects of type
    // String.
    for(int i=0;i<

              Array.getLength(v3);i++){
      for(int j=0;j<
               Array.getLength(
                 Array.get(v3,i));j++){
        Array.set(Array.get(v3,i), j, 
                    "b" + (i+1)*(j+1));
      }//end inner loop
    }//end outer loop
    
    //Display the data encapsulated
    // in the String objects.
    for(int i=0;i<Array.getLength(v3);
                                  i++){
      for(int j=0;j<Array.getLength(
                 Array.get(v3,i));j++){
        System.out.print(Array.get(
            Array.get(v3,i), j) + " ");
      }//end inner loop
      System.out.println();
    }//end outer loop
    System.out.println(); 
    
    //Now illustrate sorting and
    // searching using methods of
    // the arrays class.   

    //Create the array object
    Object v4 = Array.newInstance(
              Class.forName(
               "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, 
                           "c"+(8-i));}
      else{Array.set(v4, i,
                          "c"+(18-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
    System.out.println();
    
    //Sort array data into
    // ascending order.
    Arrays.sort((Object[])v4);
    
    //Display the sorted data
    for(int i = 0; i < 
             Array.getLength(v4); i++){
      System.out.print(
               Array.get(v4, i) + " ");
    }//end for loop
    System.out.println();
    
    //Search for an existing String
    System.out.println(
      Arrays.binarySearch((Object[])v4,
                                "c5"));
    //Search for a non-existing String
    System.out.println(
      Arrays.binarySearch((Object[])v4,
                                "c4"));
       
  }catch(ClassNotFoundException e){
                System.out.println(e);}
  }//end main
}//end class Array08
//===================================//

Listing 12


Copyright 2002, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com

-end-
 



Page 4 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

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

Sitemap | Contact Us

Rocket Fuel