www.pudn.com > P2P file system.rar > HashTable.java


package util; 
/** 
 HashTable	class definition for vector implementation of a hash table
 
 This class is used to hash the FileInformation class 
*/

import java.util.*;			//Need for Vector
import java.io.*;			//Need for displayDistribution
 

/** 
 class HashTable 
*/  
public class HashTable     { 
 
    private static final int DefaultTableSize = 11;
	public static final int HASH_BY_FILE_NAME=1;               
	public static final int HASH_BY_FILE_LOCATION=2;

    private Vector [] table;		//The buckets
    private int size;			//Number of vectors in hash table
    private int items;			//Number of items stored in hash table
	private int hashBy;
	
	//private File rescource;
     
   //Create a hash table of default size 
    public HashTable() 
    { 
		this(DefaultTableSize,1);
	} 
    	
    public HashTable(int hashBy)
    { 
		this(DefaultTableSize,hashBy);
	} 
   //Create a hash table of a user-defined size
   // n is the specified size of the hash table
    public HashTable(int n,int hashBy) 
    {
		// Initialize the buckets
		table = new Vector[n];
		this.hashBy = hashBy;
		
		// Initialize each bucket a new vector
		for (int i=0; i0)?(key%m):(0-key%m) );
    }//end hash
	
	
    //isEmpty -- determine whether hash table is empty  
    public boolean isEmpty() 
    { 
		return size()==0;   // If no items, means empty
	} 

   //hashCode -- get hash code for an object  
    public int hashCode(Object x) 
    {
		if(hashBy == this.HASH_BY_FILE_NAME)
			return hash(((FileInformation)x).getFileName(), size); // Call method hash
		else
			return hash(((FileInformation)x).getFileLocation(), size);
	}
    	
    //size -- get number of entries in hash table
    public int size()
    { 
		return items;   // Return the number of items in the table
	}
 
  //find -- determine whether item is in hash table (updates bucket)
    public boolean findItem(Object x)
    {
		// If the bucket contains the object x, return true
		// else , return false , meaning no such object
		Vector temp = table[hashCode(x)];

		for (int i=0;i