Exercises

Included below are short-answer and programming exercises. Answers are provided for those exercises whose exercise number is a hyperlink. Because college faculty use these exercises in their exams, we have provided answers to roughly half of the exercises included here.


23.5 Define each of the following terms in the context of hashing:

  1. application key.
  2. collision.
  3. hashing transformation.
  4. load factor.
  5. space/time trade-off.
  6. Hashtable class.
  7. capacity of a Hashtable.

23.6 Explain briefly the operation of each of the following methods of class Vector:

  1. addElement.
  2. insertElementAt.
  3. setElementAt.
  4. removeElement.
  5. removeAllElements.
  6. removeElementAt.
  7. firstElement.
  8. lastElement.
  9. isEmpty.
  10. contains.
  11. indexOf.
  12. trimToSize.
  13. size.
  14. capacity.

23.7 Explain why inserting additional elements into a Vector object whose current size is less than its capacity is a relatively fast operation and why inserting additional elements into a Vector object whose current size is at capacity is a relatively slow operation.

23.8 In the text we state that the default capacity increment of doubling the size of a Vector may seem wasteful of storage, but it is actually an efficient way for Vectors to grow quickly to be "about the right size." Explain this statement. Explain the pros and cons of this doubling algorithm. What can a program do when it determines that the doubling is wasting space?

23.9 Explain the use of the Enumeration interface with objects of class Vector.

23.10 By extending class Vector, Java’s designers were able to create class Stack quickly. What are the negative aspects of this use of inheritance, particularly for class Stack?

23.11 Explain briefly the operation of each of the following methods of class Hashtable:

  1. put.
  2. get.
  3. remove.
  4. isEmpty.
  5. containsKey.
  6. contains.
  7. clear.
  8. elements.
  9. keys.

23.12 Explain how to use the Random class to create pseudorandom numbers with the kind of repeatability we need for debugging.

23.13 Use a Hashtable to create a reusable class for choosing one of the 13 predefined colors in class Color. The color names should be used as keys and the predefined Color objects should be used as values. Place this class in a package that can be imported into any Java program. Use your new class in an application that allows the user to select a color and draw a shape in that color.

23.14 Modify your solution to Exercise 13.18–the polymorphic painting program–to store every shape the user draws in a Vector of MyShape objects. For the purpose of this exercise, create your own Vector subclass called ShapeVector that manipulates only MyShape objects. Provide the following capabilities in your program:

  1. Allow the user of the program to remove any number of shapes from the Vector by clicking an Undo button.
  2. Allow the user to select any shape on the screen and move it to a new location. This requires the addition of a new method to the MyShape hierarchy. The method’s first line should be public boolean isInside()

    This method should be overridden for each subclass of MyShape to determine if the coordinates where the user pressed the mouse button are inside the shape.

  3. Allow the user to select any shape on the screen and change its color.
  4. Allow the user to select any shape on the screen that can be filled or unfilled and change its fill state.

23.15 What does it mean when we state that a Properties object is a "persistent" Hashtable object? Explain the operation of each of the following methods of the Properties class:

  1. load.
  2. store.
  3. getProperty.
  4. propertyNames.
  5. list.

23.16 Why might you want to use objects of class BitSet? Explain the operation of each of the following methods of class BitSet:

  1. set.
  2. clear.
  3. get.
  4. and.
  5. or.
  6. xor.
  7. size.
  8. equals.
  9. clone.
  10. toString
  11. hashCode.

23.17 Write a program that right shifts an integer variable 4 bits with sign extension and then right shifts the same integer variable 4 bits with zero extension. The program should print the integer in bits before and after each shift operation. Run your program once with a positive integer and run it again with a negative integer.

23.18 Show how shifting an integer left by 1 can be used to simulate multiplication by 2 and how shifting an integer right by 1 can be used to simulate division by 2. Be careful to consider issues related to the sign of an integer.

23.19 Write a program that reverses the order of the bits in an integer value. The program should input the value from the user and call method reverseBits to print the bits in reverse order. Print the value in bits both before and after the bits are reversed to confirm that the bits are reversed properly. You might want to implement both a recursive and an iterative solution.

23.20 Modify your solution to Exercise 22.10 to use class Stack.

23.21 Modify your solution to Exercise 22.12 to use class Stack.

23.22 Modify your solution to Exercise 22.13 to use class Stack.


Selected Answers

Included below are answers to approximately half the of the exercises in the Cyber Classroom. We are not able to include answers to every exercise because college faculty use these exercises in their classroom exams.


 23.5 Define each of the following terms in the context of hashing:

  1. application key.
    ANS: Value used to determine the hash table cell where the data is stored.
  2. collision.
    ANS: A situation where two keys hash into the same cell.
  3. hashing transformation.
    ANS: A high-speed scheme for converting a application key into a table cell.
  4. load factor.
    ANS: The ratio of the number of occupied cells in the hash table to the size of the hash table.
  5. space/time trade-off.
    ANS: When the load factor is increased, the result is better memory utilization. However, the program runs slower due to increased hashing collisions.
  6. Hashtable class.
    ANS: Java utilities package class that enables programmers to use hashing.
  7. capacity of a Hashtable.
    ANS: The number of cells in a hash table.

23.6 Explain briefly the operation of each of the following methods of class Vector:

  1. addElement.
    ANS: Adds one element to the end of the vector.
  2. insertElementAt.
    ANS: Inserts one element at the specified position.
  3. setElementAt.
    ANS: Sets the element at the specified position.
  4. removeElement.
    ANS: Removes the first occurance of an element from the vector.
  5. removeAllElements.
    ANS: Removes all vector elements.
  6. removeElementAt.
    ANS: Removes the element at the specified position.
  7. firstElement.
    ANS: Returns a reference to the first element in the vector.
  8. lastElement.
    ANS: Returns a reference to the last element in the vector.
  9. isEmpty.
    ANS: Determines whether or not a vector is empty.
  10. contains.
    ANS: Determines if a vector contains a specified search key.
  11. indexOf.
    ANS: Returns the position of the first occurance of a specified object.
  12. trimToSize.
    ANS: Cuts the capacity of the vector to the current number of elements.
  13. size.
    ANS: The current number of elements in the vector.
  14. capacity.
    ANS: The number of elements available for storage (used and unused).

23.11 Explain briefly the operation of each of the following methods of class Hashtable:

  1. put.
    ANS: Places the specified key in the specified value.
  2. get.
    ANS: Locates the value associated with the specified key.
  3. remove.
    ANS: Removes the value associated with the specified key.
  4. isEmpty.
    ANS: Returns a boolean value indicating whether or not the hash table is empty.
  5. containsKey.
    ANS: Determines if a value associated with the specified key is in the hash table.
  6. contains.
    ANS: Determines if the specified object is in the hash table.
  7. clear.
    ANS: Empties the hash table.
  8. elements.
    ANS: Obtains an Enumeration of the values in the hash table.
  9. keys.
    ANS: Obtains an Enumeration of the keys in the hash table.

23.16 Why might you want to use objects of class BitSet?
ANS: To manipulate bits sets. Bit sets are useful for representing a set of boolean flags.

Explain the operation of each of the following methods of class BitSet:

  1. set.
    ANS: Sets the specified bit to on.
  2. clear.
    ANS: Sets the specified bits to off.
  3. get.
    ANS: Determines whether or not the specified bit is on.
  4. and.
    ANS: Performs a bitwise logical AND.
  5. or.
    ANS: Performs a bitwise logical OR.
  6. xor.
    ANS: Performs a bitwise logical XOR.
  7. size.
    ANS: Returns the size of the bit set.
  8. equals.
    ANS: Compares two bit sets for equality.
  9. clone.
    ANS: Clones the bit set.
  10. toString
    ANS: Converts a bit set to a String.
  11. hashCode.
    ANS: Provides a hash code that can be used with hash tables. 

23.17

// Exercise 23.17 Solution
// BitShift.java
// Using the bitwise shift operators
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BitShift extends JFrame {
   private JTextField bits1, bits2, bits3;

   public BitShift()
   {
      super( "Shifting bits" );

      Container c = getContentPane();
      c.setLayout( new FlowLayout() );
      bits1 = new JTextField( 33 );
      bits2 = new JTextField( 33 );
      bits3 = new JTextField( 33 );
      c.add( new JLabel( "Integer to shift " ) );

      final JTextField value = new JTextField( 12 );
      value.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               int val = Integer.parseInt( value.getText() );
               bits1.setText( getBits( val ) );
               rightShift( val );
               rightShiftSign( val );
            }
         }
      );                   
      c.add( value );      
      
      bits1.setEditable( false );
      c.add( bits1 ); 
      c.add( new JLabel( "Bits right shifted 4 positions with >>" ) );
      c.add( bits2 );
      c.add( new JLabel( "Bits right shifted 4 positions with >>>" ) );      
      c.add( bits3 );           
      setSize( 400, 200 );
      show();
   }

   private void rightShift( int number )
   {      
      number >>= 4;
      bits2.setText( getBits( number ) );
   }

   public void rightShiftSign( int number )
   {
      number >>>= 4;
      bits3.setText( getBits( number ) );
   }

   private String getBits( int value )
   {
      int displayMask = 1 << 31;
      StringBuffer buf = new StringBuffer( 35 );

      for ( int c = 1; c <= 32; c++ ) {
         buf.append(
            ( value & displayMask ) == 0 ? '0' : '1' );
         value <<= 1;

         if ( c % 8 == 0 )
            buf.append( ' ' );
      }

      return buf.toString();
   }

   public static void main( String args[] )
   {
      BitShift app = new BitShift();
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }
}


/**************************************************************************
 * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall.     *
 * All Rights Reserved.                                                   *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 *************************************************************************/

23.18

// Exercise 23.18 Solution
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BitShift extends JFrame {

   public BitShift()
   {
      super( "Shifting bits" );

      Container c = getContentPane();
      c.setLayout( new FlowLayout() );
      final JTextField bits = new JTextField( 33 );
      c.add( new JLabel( "Integer to shift " ) );

      final JTextField value = new JTextField( 12 );
      value.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               int val = Integer.parseInt( value.getText() );
               bits.setText( getBits( val ) );
            }
         }
      );                   
      c.add( value );      
      
      bits.setEditable( false );
      c.add( bits );      

      JButton left = new JButton( "multiply by 2" );
      left.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               int val = Integer.parseInt( value.getText() );
               val <<= 1;
               value.setText( Integer.toString( val ) );
               bits.setText( getBits( val ) );
            }
         }
      );
      c.add( left );      

      JButton rightSign = new JButton( "divide by 2" );
      rightSign.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               int val = Integer.parseInt( value.getText() );
               val >>= 1;
               value.setText( Integer.toString( val ) );
               bits.setText( getBits( val ) );              
            }
         }
      );                    
      c.add( rightSign );      
      setSize( 400, 120 );
      show();
   }

   private String getBits( int value )
   {
      int displayMask = 1 << 31;
      StringBuffer buf = new StringBuffer( 35 );

      for ( int c = 1; c <= 32; c++ ) {
         buf.append(
            ( value & displayMask ) == 0 ? '0' : '1' );
         value <<= 1;

         if ( c % 8 == 0 )
            buf.append( ' ' );
      }

      return buf.toString();
   }

   public static void main( String args[] )
   {
      BitShift app = new BitShift();
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }
}


/**************************************************************************
 * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall.     *
 * All Rights Reserved.                                                   *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 *************************************************************************/

23.19

// Exercise 23.19 Solution
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BitShift extends JFrame {

   public BitShift()
   {
      super( "Shifting bits" );

      Container c = getContentPane();
      c.setLayout( new FlowLayout() );
      final JTextField bits = new JTextField( 33 );
      final JTextField bits2 = new JTextField( 33 );
      c.add( new JLabel( "Integer to shift " ) );

      final JTextField value = new JTextField( 12 );
      value.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               int val = Integer.parseInt( value.getText() );
               bits.setText( getBits( val ) );
               bits2.setText( getBits( reverseBits( val ) ) );
            }
         }
      );                   
      c.add( value );      
      
      bits.setEditable( false );
      c.add( bits ); 
      c.add( new JLabel( "Reversed bits:" ) );     
      c.add( bits2 );
      setSize( 400, 150 );
      show();
   }

   public int reverseBits( int value )
   {
      int mask = 1, temp = 0;

      for ( int x = 0; x <= 31; x++ ) {
         temp <<= 1;
         temp |= ( value & mask );
         value >>= 1;
      }

      return temp;
   }

   private String getBits( int value )
   {
      int displayMask = 1 << 31;
      StringBuffer buf = new StringBuffer( 35 );

      for ( int c = 1; c <= 32; c++ ) {
         buf.append(
            ( value & displayMask ) == 0 ? '0' : '1' );
         value <<= 1;

         if ( c % 8 == 0 )
            buf.append( ' ' );
      }

      return buf.toString();
   }

   public static void main( String args[] )
   {
      BitShift app = new BitShift();
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }
}


/**************************************************************************
 * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall.     *
 * All Rights Reserved.                                                   *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 *************************************************************************/