Source of LinearArray.java


  1: // Fig 16.2: LinearArray.java
  2: // Class that contains an array of random integers and a method 
  3: // that will search that array sequentially.
  4: import java.util.Random;
  5: 
  6: public class LinearArray
  7: {
  8:    private int[] data; // array of values
  9:    private static Random generator = new Random();
 10: 
 11:    // create array of given size and fill with random integers
 12:    public LinearArray( int size )
 13:    {
 14:       data = new int[ size ]; // create space for array
 15: 
 16:       // fill array with random ints in range 10-99
 17:       for ( int i = 0; i < size; i++ )
 18:          data[ i ] = 10 + generator.nextInt( 90 );
 19:    } // end LinearArray constructor
 20: 
 21:    // perform a linear search on the data
 22:    public int linearSearch( int searchKey )
 23:    {
 24:       // loop through array sequentially
 25:       for ( int index = 0; index < data.length; index++ )
 26:          if ( data[ index ] == searchKey )
 27:             return index; // return index of integer
 28: 
 29:       return -1; // integer was not found      
 30:    } // end method linearSearch
 31: 
 32:    // method to output values in array
 33:    public String toString()
 34:    {
 35:       StringBuffer temporary = new StringBuffer();
 36: 
 37:       // iterate through array
 38:       for ( int element : data )
 39:          temporary.append( element + " " );
 40: 
 41:       temporary.append( "\n" ); // add endline character
 42:       return temporary.toString();
 43:    } // end method toString
 44: } // end class LinearArray
 45: 
 46: 
 47: /**************************************************************************
 48:  * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
 49:  * Pearson Education, Inc. All Rights Reserved.                           *
 50:  *                                                                        *
 51:  * DISCLAIMER: The authors and publisher of this book have used their     *
 52:  * best efforts in preparing the book. These efforts include the          *
 53:  * development, research, and testing of the theories and programs        *
 54:  * to determine their effectiveness. The authors and publisher make       *
 55:  * no warranty of any kind, expressed or implied, with regard to these    *
 56:  * programs or to the documentation contained in these books. The authors *
 57:  * and publisher shall not be liable in any event for incidental or       *
 58:  * consequential damages in connection with, or arising out of, the       *
 59:  * furnishing, performance, or use of these programs.                     *
 60:  *************************************************************************/