7.10 ARRAYS AND THEIR INITIALIZATION IN JAVA


7.10 ARRAYS AND THEIR INITIALIZATION IN JAVA

An array in Java is created by a declaration such as:

     int[] data = new int[3]; 

or by a statement that includes initialization:

     int[] data = new int[ ] {2, 4, 7}; 

Here is an example of the latter declaration for the case of strings:

     String[] str = new String[] {"Peter", "Paul", "Mary"}; 

When declaring Java arrays with initialization as shown above, you never explicitly specify the array dimension on the left. The compiler infers the dimension of the array from the number of elements inside the initializer. A shorter form of an array declaration with initialization is:

    int[] data = {2, 4, 7}; 

The default-initialization issues related to C++ arrays simply do not arise for Java arrays. Recall that in C++ the default initialization of an array of a primitive type depends on whether the array is in file scope or in block scope, and, for arrays of class types, it depends additionally on the no-arg constructor of the class.

On the other hand, whenever you create a new array in Java by using new, the array elements get automatically initialized to the number 0 for int arrays, to the null character (\u0000) for arrays for chars, to 0. Of for floating point arrays, to 0.0 for arrays of doubles, to false for arrays of booleans, and, finally, to the null object reference for arrays of class type objects.

Note especially the last clause above: an array of class-type objects is always default-initialized so as to hold the null reference in each of its elements. So given a class

      class User {         String name;         int age;         public User( String nam, int yy ) {             name = nam;             age = yy;         }      } 

let's declare an array of User elements by, say,

     User[] user_list = new User[10]; 

Each element of the user_list array will be default-initialized to hold the null reference.[10] After such an array is created, we are free to store in each element an object reference of type User, as in the following example for the i-th element of the array:

     user_list[i] = new User( "Zaphod", 129 ); 

The following example demonstrates the fact that when an array of class type objects is first created in Java, each element is default-initialized to a hold the null reference. The output produced by the print loop in main is just null null null null for the declared array of four User type objects. This fact is independent of whether or not the class possesses a no-arg constructor, or on the nature of the constructors actually provided for the class.

 
//ArrayBasic.java class User { String name; int age; public User( String nam, int yy ) { name = nam; age = yy; } } class Test { public static void main( String[] args ) { User[] user_list = new User[ 4 ]; for ( int i=0; i<user_list.length; i++ ) System.out.print( user_list[ i ] + " " ); // null null null null } }

7.10.1 A Java Array Is an Object

When you define a Java array by saying

        class User { String name; int age; }        User[] userList = new User[ 10 ]; 

you create a class type object of the user-defined type User[]. And suppose you extend the class User by defining two additional subclasses, StudentUser and StaffUser:

    class StaffUser extends User {String staffStatus;}    class StudentUser extends User {String schoolEnrolled;} 

and then define two new arrays for these new subclasses:

    StaffUser[] staffList = new StaffUser[30];        StudentUser[] studentList = new StudentUser[200]; 

These definitions create the hierarchy of classes shown in Figure 7.1.

click to expand
Figure 7.1

Being class type objects, arrays exhibit polymorphism just like other class type objects in Java. (The concept of polymorphism, introduced earlier in Chapter 3, will be discussed more fully in Chapter 15.) What that implies is that an array reference can be used wherever an Object reference is called for. For example, an array of type StaffUser[] could be assigned to a variable of type Object and the value of that variable cast back to a variable of type StaffUser[]:

      StaffUser[] staffList = new StaffUser[30];      Object ob = staffList;      StaffUser[] us = (StaffUser[]) ob; 

Again, by virtue of being class type objects, one can associate data members with Java arrays. In fact, all Java arrays are supplied with the data member length that evaluates to the number of elements in the array. So with the above declarations,

    int len = staffList.length; 

would give a value of 30 to the variable len.

The discussion here should not be construed to imply that the arrays of only the user-defined types belong to the object hierarchy in Java. All arrays are objects in Java, including int[], double[], float[], and so on.

Unlike C and C++, a subscript used for indexing a Java array is range checked. An out-of-range access if attempted will throw an IndexOutOfBoundsException at run time.

7.10.2 java.lang.Arrays Class for Sorting, Searching, and so on

The java.lang.Arrays class has a number of very useful methods for array processing. The methods provided can be divided into the following four categories:

fill methods: These methods fill an entire array, or a portion thereof, with a given element value. Different overload definitions of fill are for arrays of different types; each primitive type has its own fill method. There are also fill methods for arrays of Object type. For the two-argument versions of these methods, the first argument is the array that needs to be filled, and the second argument the element value for the fill. For the four-argument versions, the first argument is the array to be filled, the second argument the beginning index where the filling is to start, the third argument one past the ending index, and the last argument the element value for the fill.

binary search methods: These methods search for a given element value in an array. Different overload definitions of the method binarySearch are for arrays of different types. Each primitive type has its own binarySearch methods; there are also binarySearch methods for arrays of Object type.

sort methods: These methods are for sorting arrays of different types. The sort methods for the arrays of primitive types are based on a tuned quicksort algorithm described by Bentley and Mcllroy [3]. For an array of N elements, this algorithm sorts with a computational complexity of O(Nlog(N)) on most data sets on which a regular implementation of quicksort would work with N2 performance. The sort methods for arrays of Object type are based on the mergesort algorithm. An important issue related to the sorting of arrays of class-type objects is whether the object that are deemed to be equal according to the comparison criterion used for sorting will maintain their respective positions in the sorted list. Algorithms that do not alter the relative positioning of equal elements are called stable.[11] Merge sort guarantees stability, with a guaranteed computational complexity of O(Nlog(N)).

In addition, java.util.Arrays class also comes with a special method, asList, that returns a List composed of the array elements. This method can be used as a bridge between array-based and collection-based methods. Any changes made to the List constructed in this manner are reflected in the underlying array.

The following program illustrates the fill and the binarySearch methods. The example shows these methods for only a couple of the primitive types. But note that these two methods are available for all primitive types and for the Object type.

 
//ArraysFill.java import java.util.*; class Test { public static void main( String[] args ) { int[] intArr = new int[4]; Arrays.fill( intArr, 99 ); //(A) for ( int i=0; i<intArr.length; i++ ) System.out.print( intArr[ i ] + " " ); // 99 99 99 99 System.out.println(); double[] dbArr = new double[4]; Arrays.fill( dbArr, 2, 3, 9.9 ); //(B) for ( int i=0; i<dbArr.length; i++ ) System.out.print( dbArr[ i ] + " " ); // 0.0 0.0 9.9 0.0 System.out.println(); int pos = Arrays.binarySearch( dbArr, 9.9 ); //(C) System.out.println( pos ); // 2 } }

We first declare, intArr, an int array of four elements. This array will be default-initialized to the integer 0. We then use the two-argument version of Arrays.fill in line (A) to fill the array with the integer 99. Next, we construct dbArr, a double array of four elements. This array is default-initialized to the number 0.0. In line (B) we invoke a four-argument version of fill to only partially fill the array with the number 9.9. Finally, we show in line (C) how Arrays.binarySearch can be invoked to search for the number 9.9 in the array dbArr.

The next example shows how useful it can be to convert an array into a List. The class List comes with a method called shuffle that randomizes the elements of a list; each element of the list is moved to a randomly chosen position in the list. In the program below, we use the shuffle method of List to construct an array of random numbers. In lines (A) and (B), the program fills an Integer array with Integer objects for a consecutive set of integers from 0 through 9, both inclusive. Line (C) then converts this array into a List object, on which is invoked the shuffle method in line (D). We convert the List object back into an array in line (E) by invoking the toArray method on the list. We finally print out the contents of the array in line (F). As the reader can see, we have an array of random numbers. Note that since Arrays.asList can only be invoked on arrays of type Object, we must use the wrapper class Integer as shown.

 
//ArraysShuffle.java import java.util.*; class Test { public static void main( String[] args ) { Integer[] intArr2 = new Integer[10]; //(A) for ( int i=0; i<intArr2.length; i++ ) //(B) intArr2[i] = new Integer(i); List list = Arrays.asList( intArr2 ); //(C) Collections.shuffle( list ); //(D) Integer[] intArr3 = (Integer[]) list.toArray(); //(E) for ( int i=0; i<intArr2.length; i++ ) //(F) System.out.print( intArr3[ i ].intValue() + " " ); //98513472 6 0 (different with each run) System.out.println(); } }

[10]A Java array of class type objects is analogous to a C++ array of pointers, especially when, at the time the array is created, each pointer in the array is initialized to 0, the null pointer.

[11]See Chapter 5 for further discussion on and for an example of stable sorting.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net