Class Arrays

Class Arrays provides static methods for manipulating arrays. In Chapter 7, our discussion of array manipulation was low level in the sense that we wrote the actual code to sort and search arrays. Class Arrays provides high-level methods, such as sort for sorting an array, binarySearch for searching a sorted array, equals for comparing arrays and fill for placing values into an array. These methods are overloaded for primitive-type arrays and Object arrays. In addition, methods sort and binarySearch are overloaded with generic versions that allow programmers to sort and search arrays containing objects of any type. Figure 19.2 demonstrates methods fill, sort, binarySearch and equals. Method main (lines 6585) creates a UsingArrays object and invokes its methods.

Figure 19.2. Arrays class methods.

(This item is displayed on pages 908 - 909 in the print version)

 1 // Fig. 19.2: UsingArrays.java
 2 // Using Java arrays.
 3 import java.util.Arrays;
 4
 5 public class UsingArrays
 6 {
 7 private int intArray[] = { 1, 2, 3, 4, 5, 6 };
 8 private double doubleArray[] = { 8.4, 9.3, 0.2, 7.9, 3.4 };
 9 private int filledIntArray[], intArrayCopy[];
10
11 // constructor initializes arrays
12 public UsingArrays()
13 {
14 filledIntArray = new int [ 10 ]; // create int array with 10 elements
15 intArrayCopy = new int [ intArray.length ];
16
17 Arrays.fill( filledIntArray, 7 ); // fill with 7s 
18 Arrays.sort( doubleArray ); // sort doubleArray ascending
19
20 // copy array intArray into array intArrayCopy
21 System.arraycopy( intArray, 0, intArrayCopy, 
22  0, intArray.length ); 
23 } // end UsingArrays constructor
24
25 // output values in each array
26 public void printArrays()
27 {
28 System.out.print( "doubleArray: " );
29 for ( double doubleValue : doubleArray )
30 System.out.printf( "%.1f ", doubleValue );
31
32 System.out.print( "
intArray: " );
33 for ( int intValue : intArray )
34 System.out.printf( "%d ", intValue );
35
36 System.out.print( "
filledIntArray: " );
37 for ( int intValue : filledIntArray )
38 System.out.printf( "%d ", intValue );
39
40 System.out.print( "
intArrayCopy: " );
41 for ( int intValue : intArrayCopy )
42 System.out.printf( "%d ", intValue );
43
44 System.out.println( "
" );
45 } // end method printArrays
46
47 // find value in array intArray
48 public int searchForInt( int value )
49 {
50 return Arrays.binarySearch( intArray, value );
51 } // end method searchForInt
52
53 // compare array contents
54 public void printEquality()
55 {
56 boolean b = Arrays.equals( intArray, intArrayCopy );
57 System.out.printf( "intArray %s intArrayCopy
",
58 ( b ? "==" : "!=" ) );
59
60 b = Arrays.equals( intArray, filledIntArray );
61 System.out.printf( "intArray %s filledIntArray
",
62 ( b ? "==" : "!=" ) );
63 } // end method printEquality
64
65 public static void main( String args[] )
66 {
67 UsingArrays usingArrays = new UsingArrays();
68
69 usingArrays.printArrays();
70 usingArrays.printEquality();
71
72 int location = usingArrays.searchForInt( 5 );
73 if ( location >= 0 )
74 System.out.printf(
75 "Found 5 at element %d in intArray
", location );
76 else
77 System.out.println( "5 not found in intArray" );
78
79 location = usingArrays.searchForInt( 8763 );
80 if ( location >= 0 )
81 System.out.printf(
82 "Found 8763 at element %d in intArray
", location );
83 else
84 System.out.println( "8763 not found in intArray" );
85 } // end main
86 } // end class UsingArrays
 
doubleArray: 0.2 3.4 7.9 8.4 9.3
intArray: 1 2 3 4 5 6
filledIntArray: 7 7 7 7 7 7 7 7 7 7
intArrayCopy: 1 2 3 4 5 6

intArray == intArrayCopy
intArray != filledIntArray
Found 5 at element 4 in intArray
8763 not found in intArray
 

Line 17 calls static method fill of class Arrays to populate all 10 elements of filledIntArray with 7s. Overloaded versions of fill allow the programmer to populate a specific range of elements with the same value.

Line 18 sorts the elements of array doubleArray. The static method sort of class Arrays orders the array's elements in ascending order by default. We discuss how to sort in descending order later in the chapter. Overloaded versions of sort allow the programmer to sort a specific range of elements.

Lines 2122 copy array intArray into array intArrayCopy. The first argument (intArray) passed to System method arraycopy is the array from which elements are to be copied. The second argument (0) is the index that specifies the starting point in the range of elements to copy from the array. This value can be any valid array index. The third argument (intArrayCopy) specifies the destination array that will store the copy. The fourth argument (0) specifies the index in the destination array where the first copied element should be stored. The last argument specifies the number of elements to copy from the array in the first argument. In this case, we copy all the elements in the array.

Line 50 calls static method binarySearch of class Arrays to perform a binary search on intArray, using value as the key. If value is found, binarySearch returns the index of the element; otherwise, binarySearch returns a negative value. The negative value returned is based on the search key's insertion pointthe index where the key would be inserted in the array if we were performing an insert operation. After binarySearch determines the insertion point, it changes its sign to negative and subtracts 1 to obtain the return value. For example, in Fig. 19.2, the insertion point for the value 8763 is the element with index 6 in the array. Method binarySearch changes the insertion point to 6, subtracts 1 from it and returns the value 7. Subtracting 1 from the insertion point guarantees that method binarySearch returns positive values (>=0) if and only if the key is found. This return value is useful for inserting elements in a sorted array. Chapter 16, Searching and Sorting, discusses binary searching in detail.

Common Programming Error 19.1

Passing an unsorted array to binarySearch is a logic errorthe value returned is undefined.

Lines 56 and 60 call static method equals of class Arrays to determine whether the elements of two arrays are equivalent. If the arrays contain the same elements in the same order, the method returns true; otherwise, it returns false. The equality of each element is compared using Object method equals. Many classes override method equals to perform the comparisons in a manner specific to those classes. For example, class String declares equals to compare the individual characters in the two Strings being compared. If method equals is not overridden, the original version of method equals inherited from class Object is used.

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

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