» נושאי לימוד
» נושאי לימוד
יום שני 29 באפריל 2024
רישום תוכנית
דף ראשי  מתקדמים  וקטורים, Hashtables ורשימות  תוכנית דוגמא  רישום תוכנית גרסה להדפסה

רישום תוכנית

להלן רישום תוכנית מלא כך שתוכל לראות את חלקי הקוד המעניינים בתוך הקשר.

 

/*File Hash01.java Copyright 1997, R.G.Baldwin
This program is not intended to accomplish anything
particularly useful other than to illustrate how to use
the Vector and Hashtable, and the Enumeration 
interface.

This program was tested using JDK 1.1.3 under Win95.

The output from the program is:
  
In AgeCompare method
Tom is not younger than Dick
In AgeCompare method
Harry is younger than Dick
In AgeCompare method
Harry is younger than Tom
In WeightCompare method
Tom is not lighter than Dick
In WeightCompare method
Harry is lighter than Dick
In WeightCompare method
Harry is lighter than Tom
Invalid Key, could throw exception here
Invalid Key, could throw exception here
Invalid Key, could throw exception here
**********************************************************/
import java.util.*;
//=======================================================//

//This is the controlling class used to test everything
// else.
class Hash01{
  public static void main(String[] args){
    //Instantiate a manager to handle the comparisons
    CompareManager compareManager = new CompareManager();
    
    //Register three pairs of data objects with the
    // manager
    compareManager.registerPair(new Data("Tom",65,180),
                                 new Data("Dick",60,170));
    compareManager.registerPair(new Data("Harry",40,160),
                                 new Data("Dick",60,170));
    compareManager.registerPair(new Data("Harry",40,160),
                                  new Data("Tom",65,180));

    //Request comparison of all pairs of objects on the
    // basis of age and weight (separately). Also
    // request comparison on the basis of an invalid
    // parameter.
    compareManager.compareAll(CompareHow.AGE);
    compareManager.compareAll(CompareHow.WEIGHT);
    compareManager.compareAll(CompareHow.INVALID);
  }//end main
}//end class Hash01
//=======================================================//

//This is the class used to package the data for
// submission to the comparison manager.
class Data{
  String name;
  int age;
  int weight;
  
  Data(String name,int age,int weight){
    this.name = name;
    this.age = age;
    this.weight = weight;
  }//end constructor
}//end class Data
//=======================================================//

//Define some string constants that are used later as
// keys in a hash table.
class CompareHow{
  public static final String AGE = "AGE";
  public static final String WEIGHT = "WEIGHT";
  public static final String INVALID = "INVALID";
}//end class CompareHow
//=======================================================//

//Define the Comparable interface.  Note that it declares
// the method named comparePair() that is defined in
// several classes that implement the interface.
interface Comparable{
  public void comparePair(String how,Object obj1,
                                             Object obj2);
}//end Comparable interface
//=======================================================//

//This class is used to manage the process of comparing
// pairs of objects
class CompareManager{
  //Stores a reference to an object that does the work
  // of comparing objects on the basis of a String
  // parameter that define how the objects are to be 
  // compared.
  Object compareTool;
  
  //Stores a list of references to objects each of which
  // contains a pair of objects to be compared.
  Vector myListOfObjects;
  //_____________________________________________________//
  
  //Define an inner class of the CompareManager class
  // that is used to package a pair of incoming 
  // objects into a single object for storage in a
  // Vector object.
  class PairOfObj{
    Object obj1;
    Object obj2;
    
    PairOfObj(Object obj1,Object obj2){//constructor
      this.obj1 = obj1;
      this.obj2 = obj2;
    }//end constructor
  }//end inner-class PairOfObj
  //_____________________________________________________//
  
  CompareManager(){//constructor for a manager object
    //Instantiate a tool object which will be used to 
    // actually perform the comparisons
    this.compareTool = new CompareTool();
    //Instantiate a Vector object to contain a list of 
    // registered objects
    myListOfObjects = new Vector();
  }//end constructor
  //-----------------------------------------------------//

  //This method maintains a list of registered objects
  // in a Vector object where each registered object 
  // contains a pair of objects that are to be compared 
  // later all at the same time.
  public void registerPair(Object obj1,Object obj2) {
    this.myListOfObjects.addElement(
                                 new PairOfObj(obj1,obj2));
  }//end registerPair
  //-----------------------------------------------------//
 
  //This method compares all the pairs of objects contained
  // in the list of registered objects. The comparison is
  // performed on the basis of the how parameter (age or
  // weight).
  public void compareAll(String how){
    //Create an enumeration object for the objects in the 
    // list of registered objects.
    Enumeration myEnum = myListOfObjects.elements();
    
    //Use the enumeration object to process all the objects
    // in the list of registered objects.  Each registered
    // object contains a pair of objects that are to be
    // compared.
    while(myEnum.hasMoreElements()){
      //Get the next registered object
      Object aPairOfObj = myEnum.nextElement();
      //Extract and compare the pair of objects contained
      // in the registered object.
      ((Comparable)compareTool).comparePair(how,
                             ((PairOfObj)aPairOfObj).obj1,
                             ((PairOfObj)aPairOfObj).obj2);
    }//end while loop
  }//end compareAll
}//end CompareManager class
//=======================================================//

//This class is used to instantiate an object which
// performs the actual comparisons based on a parameter
// named how and using references to methods that are
// stored in a hash table along with key values that
// match the parameter named how.  The parameter named
// how is used to fetch a reference to a method from the
// hash table and that reference is used to invoke the
// method to which it refers.
class CompareTool implements Comparable{
  //Store references to different comparison methods in
  // a hash table for later reference.
  private Hashtable myHashTable = new Hashtable();
  //_____________________________________________________//
  
  //This inner class contains one of the methods used to 
  // compare objects. This one is designed to compare on 
  // the basis of the instance variable named age. Note
  // that the name of the method in this inner class is
  // the same as the name of a method in the parent class
  // of this class and is also the same as the method
  // declared in the interface named Comparable.
  private class AgeCompare implements Comparable {
    public void comparePair(String how,Object obj1,
                                             Object obj2){
      System.out.println("In AgeCompare method");
      Data temp1 = (Data)obj1;//Cast incoming objects to
      Data temp2 = (Data)obj2;// the correct type.
      //Make the comparison on age
      if(temp1.age<temp2.age)
        System.out.println(temp1.name + 
                         " is younger than " + temp2.name);
      else System.out.println(temp1.name + 
                     " is not younger than " + temp2.name);
    }//end trace()
  }//end inner-class AgeCompare
  //_____________________________________________________//

  //This inner class contains one of the methods used to 
  // compare objects. This one is designed to compare on 
  // the basis of the instance variable named weight. Note
  // that the name of the method in this inner class is
  // the same as the name of a method in the parent class
  // of this class and is also the same as the method
  // declared in the interface named Comparable.
  private class WeightCompare implements Comparable {
    public void comparePair(String how,Object obj1,
                                              Object obj2){
      System.out.println("In WeightCompare method");
      Data temp1 = (Data)obj1;//Cast incoming objects to
      Data temp2 = (Data)obj2;// the correct type.
      //Make the comparison on weight
      if(temp1.weight<temp2.weight)
        System.out.println(temp1.name + 
                         " is lighter than " + temp2.name);
      else System.out.println(temp1.name + 
                     " is not lighter than " + temp2.name);
    }//end trace()
  }//end inner-class WeightCompare
  //_____________________________________________________//

  //This is the constructor for the CompareTool class.
  // It instantiates two objects, each containing a 
  // method named comparePair() and stores references to
  // them in the hash table, each with a different key.
  // The key values are designed to match the how 
  // parameter that is passed in to specify how the 
  // comparison is to be performed.  Later, the how 
  // parameter is used to fetch the reference to a
  // particular method and that reference is used to
  // invoke the method.
  public CompareTool(){//constructor
    //Initialize myHashTable and store references to 
    // methods in a hash table using string constants from
    // the CompareHow class as keys.
    myHashTable.put( CompareHow.AGE, new AgeCompare() );
    myHashTable.put( CompareHow.WEIGHT, 
                                     new WeightCompare() );
  }//end constructor
  //-----------------------------------------------------//

  //This is the method that is called to compare two
  // objects on the basis of the how parameter.
  //Note that the name of this method is the same as the
  // name of a method in each of the inner classes, and 
  // is also the same as the name of the method declared
  // in the interface named Comparable.
  public void comparePair(String how, Object obj1,
                                              Object obj2){
    //Use incoming how parameter to extract the reference
    // to the correct method from the hash table to use for
    // this comparison and assign the reference to a local
    // variable named theMethod.  Test to confirm that the
    // value of the how parameter is actually a key in the
    // hashtable.  If not, simply display a message.  Note
    // that this would be a good place to throw an 
    // exception.
    if(myHashTable.containsKey(how)){
      Object theMethod = myHashTable.get(how);
    
      //Use the local variable named theMethod to invoke 
      // the correct comparison method on the incoming 
      // objects.
      //Note that this is the invocation of a method 
      // named comparePair() that is defined in one of 
      // the inner classes of this class and is contained
      // in the object referenced in the hash table.  It
      // is not a recursive call to this version of 
      // comparePair().
      ((Comparable)theMethod).comparePair(how,obj1,obj2 );
    }//end if
    else System.out.println(
                "Invalid Key, could throw exception here");
  }//end comparePair()
  //-----------------------------------------------------//
}//end CompareTool class
//=======================================================//

 02-12-03 / 20:23  עודכן ,  13-10-03 / 19:13  נוצר ע"י רונית רייכמן  בתאריך 
 תוכנית דוגמא - הקודםהבא - סקירה 
תגובות הקוראים    תגובות  -  0
דרכונט
מהי מערכת הדרכונט?
אינך מחובר, להתחברות:
דוא"ל
ססמא
נושאי לימוד
חיפוש  |  לא פועל
משלנו  |  לא פועל
גולשים מקוונים: 7