SlideShare a Scribd company logo
Given the code below create a method called, getCollisionCount that will return the number of
collisions that occurred. This method will be inside the hasedDictionary class. Please do not use
setNext getNext methods or any nodes just use what's provided in the code below
import java.util.Iterator;
public interface DictionaryInterface
{
/** Adds a new entry to this dictionary. If the given search key already
exists in the dictionary, replaces the corresponding value.
@param key An object search key of the new entry.
@param value An object associated with the search key.
@return Either null if the new entry was added to the dictionary
or the value that was associated with key if that value
was replaced. */
public V add(K key, V value);
/** Removes a specific entry from this dictionary.
@param key An object search key of the entry to be removed.
@return Either the value that was associated with the search key
or null if no such object exists. */
public V remove(K key);
/** Retrieves from this dictionary the value associated with a given
search key.
@param key An object search key of the entry to be retrieved.
@return Either the value that is associated with the search key
or null if no such object exists. */
public V getValue(K key);
/** Sees whether a specific entry is in this dictionary.
@param key An object search key of the desired entry.
@return True if key is associated with an entry in the dictionary. */
public boolean contains(K key);
/** Creates an iterator that traverses all search keys in this dictionary.
@return An iterator that provides sequential access to the search
keys in the dictionary. */
public Iterator getKeyIterator();
/** Creates an iterator that traverses all values in this dictionary.
@return An iterator that provides sequential access to the values
in this dictionary. */
public Iterator getValueIterator();
/** Sees whether this dictionary is empty.
@return True if the dictionary is empty. */
public boolean isEmpty();
/** Gets the size of this dictionary.
@return The number of entries (key-value pairs) currently
in the dictionary. */
public int getSize();
/** Removes all entries from this dictionary. */
public void clear();
} // end DictionaryInterface
//hasheddictionay class
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A class that implements the ADT dictionary by using hashing and
* linear probing to resolve collisions.
* The dictionary is unsorted and has distinct search key.
Search keys and associated values are not null.
*/
public class HashedDictionary implements DictionaryInterface
{
// The dictionary:
private int numberOfEntries;
private static final int DEFAULT_CAPACITY = 5; // Must be prime
private static final int MAX_CAPACITY = 10000;
// The hash table:
private Entry[] hashTable;
private int tableSize; // Must be prime
private static final int MAX_SIZE = 2 * MAX_CAPACITY;
private boolean integrityOK = false;
private static final double MAX_LOAD_FACTOR = 0.5; // Fraction of
// hash table that can be filled
protected final Entry AVAILABLE = new Entry<>(null, null);
public HashedDictionary()
{
this(DEFAULT_CAPACITY); // Call next constructor
} // end default constructor
public HashedDictionary(int initialCapacity)
{
initialCapacity = checkCapacity(initialCapacity);
numberOfEntries = 0; // Dictionary is empty
// Set up hash table:
// Initial size of hash table is same as initialCapacity if it is prime;
// otherwise increase it until it is prime size
tableSize = getNextPrime(initialCapacity);
checkSize(tableSize); // Check that size is not too large
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
Entry[] temp = (Entry[])new Entry[tableSize];
hashTable = temp;
integrityOK = true;
} // end constructor
/* Implementations of methods in DictionaryInterface are here. . . .*/
public boolean isEmpty()
{
return this.numberOfEntries == 0;
}//end isEmpty
public Iterator getValueIterator()
{
throw new NoSuchElementException("Value Iterator Not Implemented");
}//end valueIterator
public void clear()
{
checkIntegrity();
for (int index = 0; index < this.hashTable.length; index++)
{
hashTable[index] = null;
}//end of for
this.numberOfEntries = 0;
}//end clear
public Iterator getKeyIterator()
{
return new KeyIterator();
}//end iterator
public boolean contains(K key)
{
return getValue(key) != null;
}//end contains
public int getSize()
{
return this.numberOfEntries;
}//end getSize
public V remove(K key) {
checkIntegrity();
int index = getHashIndex(key);
while (hashTable[index] != null) {
if (hashTable[index].getKey().equals(key)) {
V value = hashTable[index].getValue();
hashTable[index].setValue(null);
hashTable[index] = AVAILABLE;
numberOfEntries--;
return value;
}
index = (index + 1) % hashTable.length;
}
// If the key is not found, return null
return null;
}
public V getValue(K key)
{
checkIntegrity();
V result = null;
int index = getHashIndex(key);
if ((hashTable[index] != null) && (hashTable[index] != AVAILABLE))
result = hashTable[index].getValue(); // Key found; get value
// Else key not found; return null
return result;
} // end getValue
public V add(K key, V value)
{
int index;
V oldValue;
if((key == null) || (value == null))
{
throw new NoSuchElementException();
}
index = getHashIndex(key);
if((hashTable[index] != null) && (hashTable[index] != AVAILABLE))
{
hashTable[index] = new Entry(key,value);
numberOfEntries++;
oldValue = null;
}
else
{
oldValue = hashTable[index].getValue();
hashTable[index].setValue(value);
}
if(isHashTableTooFull())
{
enlargeHashTable();
}
return oldValue;
}//end of add
/* END of Implementations of dictionary methods are here^. . . . */
/* Implementations of private methods are here. . . . */
//precondition: checkIntegrity has been called
private void enlargeHashTable()
{
Entry[] oldTable = hashTable;
int oldSize = hashTable.length;
int newSize = getNextPrime(oldSize + oldSize);
checkSize(newSize);
//The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
Entry[] temp = (Entry[]) new Entry[newSize];
hashTable = temp;
numberOfEntries = 0;//reset number of dictionary entries, since it will be incremented by add
during rehash
//rehash dictionary entries from old array to the new and bigger array;
//skip elements that contain null or available
for(int index = 0; index < oldSize; index++)
{
if((oldTable[index] != null) && (oldTable[index] != AVAILABLE))
{
add(oldTable[index].getKey(), oldTable[index].getValue());
}
}// end for
}//end enlargeHashTable
private int getHashIndex(K key)
{
int hashIndex = key.hashCode() % hashTable.length;
if(hashIndex < 0)
{
hashIndex = hashIndex + hashTable.length;
}
return hashIndex;
}//end getHashIndex
private void checkIntegrity()
{
if(!integrityOK)
{
throw new SecurityException("objecy is currupt");
}
}//end checkIntegrity
private boolean isHashTableTooFull()
{
if((numberOfEntries / hashTable.length) >= MAX_LOAD_FACTOR)
{
return true;
}
else
{
return false;
}
}//end isHashTableTooFull
private int checkSize(int size)
{
if(size >= MAX_SIZE){throw new IllegalStateException("Dictionary has become too large.");}
else{return size;}
}//end checksize
private int checkCapacity(int cap)
{
if(cap < DEFAULT_CAPACITY)
{
cap = DEFAULT_CAPACITY;
}
else if (cap > MAX_CAPACITY)
{
throw new IllegalStateException("Attempt to create a dictionary " + "whose capacity is larger
than " + MAX_CAPACITY);
}
return cap;
}//end checkcap
private int getNextPrime(int integer)
{
// if even, add 1 to make od
if (integer % 2 == 0)
{
integer++;
} // end if
// test odd integers
while (!isPrime(integer))
{
integer = integer + 2;
} // end while
return integer;
}//end getnextprime
private boolean isPrime(int integer)
{
boolean result;
boolean done = false;
// 1 and even numbers are not prime
if ( (integer == 1) || (integer % 2 == 0) )
{
result = false;
}
// 2 and 3 are prime
else if ( (integer == 2) || (integer == 3) )
{
result = true;
}
else // integer is odd and >= 5
{
assert (integer % 2 != 0) && (integer >= 5);
// a prime is odd and not divisible by every odd integer up to its square root
result = true; // assume prime
for (int divisor = 3; !done && (divisor * divisor <= integer); divisor = divisor + 2)
{
if (integer % divisor == 0)
{
result = false; // divisible; not prime
done = true;
} // end if
} // end for
} // end if
return result;
} // end isPrime
/* END of Implementations of private methods are here^. . . . */
protected final class Entry
{
private K key;
private V value;
private Entry(K searchKey, V dataValue)
{
key = searchKey;
value = dataValue;
}//end contructor
private K getKey()
{
return key;
}//end getKey
private V getValue()
{
return value;
}//end value
private void setValue(V newValue)
{
value = newValue;
}//end setValue
} // end Entry
private class KeyIterator implements Iterator
{
private int currentIndex; // Current position in hash table
private int numberLeft; // Number of entries left in iteration
private KeyIterator()
{
currentIndex = 0;
numberLeft = numberOfEntries;
} // end default constructor
public boolean hasNext()
{
return numberLeft > 0;
} // end hasNext
public void remove()
{
throw new UnsupportedOperationException();
} // end remove
public K next()
{
K result = null;
if (hasNext())
{
// Skip table locations that do not contain a current entry
while ( (hashTable[currentIndex] == null) ||
(hashTable[currentIndex] == AVAILABLE) )
{
currentIndex++;
} // end while
result = hashTable[currentIndex].getKey();
numberLeft--;
currentIndex++;
}
else
throw new NoSuchElementException();
return result;
} // end next
} // end KeyIterator
} // end HashedDictionary

More Related Content

PDF
using the code below write the public V add(K key, V value); that ad.pdf
PDF
I have created a class hasdhedDictionary that implements the Diction.pdf
PDF
using the code below create a method called getCollisionCount that w.pdf
PDF
The hashtable youll be making will use Strings as the keys and Obje.pdf
PDF
Complete code in Java The hashtable you'll be making will use String.pdf
PDF
Fill in parameters Public New Hash table (int initial Capacity, floa.pdf
PDF
Assignment4 Assignment 4 Hashtables In this assignment we w.pdf
PPTX
Hash table in java
using the code below write the public V add(K key, V value); that ad.pdf
I have created a class hasdhedDictionary that implements the Diction.pdf
using the code below create a method called getCollisionCount that w.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdf
Complete code in Java The hashtable you'll be making will use String.pdf
Fill in parameters Public New Hash table (int initial Capacity, floa.pdf
Assignment4 Assignment 4 Hashtables In this assignment we w.pdf
Hash table in java

Similar to Given the code below create a method called, getCollisionCount that .pdf (20)

PDF
Describe a data structure to represent sets of elements (each element.pdf
PPTX
18. Dictionaries, Hash-Tables and Set
PDF
This class will implement a hash table. The hash table will hold data.pdf
PDF
Do the following program in C++- Create a item class... with and i.pdf
DOCX
Assignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docx
PPTX
Lecture14_15_Hashing.pptx
PDF
Algorithms notes tutorials duniya
PDF
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
PPTX
Hash map
PPT
Google collections api an introduction
PDF
6. Generics. Collections. Streams
PPTX
How Hashmap works internally in java
PPTX
hashing in data structures and its applications
PPTX
Reference Guide to Java - Day4
PPTX
Ts project Hash based inventory system
PPTX
Hash based inventory system
PPTX
8. Hash table
PDF
Hashing components and its laws 2 types
PDF
Hashing and File Structures in Data Structure.pdf
PDF
public class LinkedHashEntry { private int key; private int valu.pdf
Describe a data structure to represent sets of elements (each element.pdf
18. Dictionaries, Hash-Tables and Set
This class will implement a hash table. The hash table will hold data.pdf
Do the following program in C++- Create a item class... with and i.pdf
Assignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docx
Lecture14_15_Hashing.pptx
Algorithms notes tutorials duniya
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
Hash map
Google collections api an introduction
6. Generics. Collections. Streams
How Hashmap works internally in java
hashing in data structures and its applications
Reference Guide to Java - Day4
Ts project Hash based inventory system
Hash based inventory system
8. Hash table
Hashing components and its laws 2 types
Hashing and File Structures in Data Structure.pdf
public class LinkedHashEntry { private int key; private int valu.pdf

More from aucmistry (20)

PDF
Consider the Project article 2 titled Readiness for Organizational .pdf
PDF
Consider the pedigree for Waardenburg syndrome which is an autosomal .pdf
PDF
Consider the imaginary nation of Leguminia, whose citizens only consu.pdf
PDF
Consider the investment projects in the table below, all of which hav.pdf
PDF
Consider the following method. Answer the following 1. Describe the w.pdf
PDF
Consider the following statistics From 2010 to 2011 GDP grew by 2.3.pdf
PDF
Consider the following table I am trying to do a substring on SELECT.pdf
PDF
Consider the following closed economy, C=480+0.8(YT),Pp=100,G=20, w.pdf
PDF
Consider the data for the mean number of days with precipitation more.pdf
PDF
Consider the following documents Doc 1 pat sat on mat Doc 2 cat sa.pdf
PDF
Consider the continuous random variable, Y, with moment generating fu.pdf
PDF
Consider the case in which query involves a single variable. Let X be.pdf
PDF
Haz un resumen del siguiente pasaje y dale un t�tulo adecuado. Has.pdf
PDF
Hay nueve filos principales descritos -Referencias - Mollusca, P.pdf
PDF
Have you ever driven through a rural area and thought, There is not.pdf
PDF
Harvey Inc. has a Current E&P balance of ($100,000) earned ratably t.pdf
PDF
Harris Corporation provides the following data on a proposed capital.pdf
PDF
HAROUN COMPANY Comparative Year-End Balance Sheets December 31, 2021.pdf
PDF
HAPTER 9 - Other Income, Other Deductions and Other IssuesIntroduc.pdf
PDF
HAP 417Watch the following 4 videos and then answer the 6 question.pdf
Consider the Project article 2 titled Readiness for Organizational .pdf
Consider the pedigree for Waardenburg syndrome which is an autosomal .pdf
Consider the imaginary nation of Leguminia, whose citizens only consu.pdf
Consider the investment projects in the table below, all of which hav.pdf
Consider the following method. Answer the following 1. Describe the w.pdf
Consider the following statistics From 2010 to 2011 GDP grew by 2.3.pdf
Consider the following table I am trying to do a substring on SELECT.pdf
Consider the following closed economy, C=480+0.8(YT),Pp=100,G=20, w.pdf
Consider the data for the mean number of days with precipitation more.pdf
Consider the following documents Doc 1 pat sat on mat Doc 2 cat sa.pdf
Consider the continuous random variable, Y, with moment generating fu.pdf
Consider the case in which query involves a single variable. Let X be.pdf
Haz un resumen del siguiente pasaje y dale un t�tulo adecuado. Has.pdf
Hay nueve filos principales descritos -Referencias - Mollusca, P.pdf
Have you ever driven through a rural area and thought, There is not.pdf
Harvey Inc. has a Current E&P balance of ($100,000) earned ratably t.pdf
Harris Corporation provides the following data on a proposed capital.pdf
HAROUN COMPANY Comparative Year-End Balance Sheets December 31, 2021.pdf
HAPTER 9 - Other Income, Other Deductions and Other IssuesIntroduc.pdf
HAP 417Watch the following 4 videos and then answer the 6 question.pdf

Recently uploaded (20)

PDF
VCE English Exam - Section C Student Revision Booklet
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Cell Types and Its function , kingdom of life
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Lesson notes of climatology university.
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Classroom Observation Tools for Teachers
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
master seminar digital applications in india
PPTX
Presentation on HIE in infants and its manifestations
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
Computing-Curriculum for Schools in Ghana
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
VCE English Exam - Section C Student Revision Booklet
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Cell Types and Its function , kingdom of life
2.FourierTransform-ShortQuestionswithAnswers.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
human mycosis Human fungal infections are called human mycosis..pptx
Lesson notes of climatology university.
Anesthesia in Laparoscopic Surgery in India
O5-L3 Freight Transport Ops (International) V1.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
Classroom Observation Tools for Teachers
O7-L3 Supply Chain Operations - ICLT Program
FourierSeries-QuestionsWithAnswers(Part-A).pdf
master seminar digital applications in india
Presentation on HIE in infants and its manifestations
Supply Chain Operations Speaking Notes -ICLT Program
A systematic review of self-coping strategies used by university students to ...
Computing-Curriculum for Schools in Ghana
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx

Given the code below create a method called, getCollisionCount that .pdf

  • 1. Given the code below create a method called, getCollisionCount that will return the number of collisions that occurred. This method will be inside the hasedDictionary class. Please do not use setNext getNext methods or any nodes just use what's provided in the code below import java.util.Iterator; public interface DictionaryInterface { /** Adds a new entry to this dictionary. If the given search key already exists in the dictionary, replaces the corresponding value. @param key An object search key of the new entry. @param value An object associated with the search key. @return Either null if the new entry was added to the dictionary or the value that was associated with key if that value was replaced. */ public V add(K key, V value); /** Removes a specific entry from this dictionary. @param key An object search key of the entry to be removed. @return Either the value that was associated with the search key or null if no such object exists. */ public V remove(K key); /** Retrieves from this dictionary the value associated with a given search key. @param key An object search key of the entry to be retrieved. @return Either the value that is associated with the search key or null if no such object exists. */ public V getValue(K key); /** Sees whether a specific entry is in this dictionary. @param key An object search key of the desired entry. @return True if key is associated with an entry in the dictionary. */ public boolean contains(K key); /** Creates an iterator that traverses all search keys in this dictionary. @return An iterator that provides sequential access to the search keys in the dictionary. */ public Iterator getKeyIterator(); /** Creates an iterator that traverses all values in this dictionary.
  • 2. @return An iterator that provides sequential access to the values in this dictionary. */ public Iterator getValueIterator(); /** Sees whether this dictionary is empty. @return True if the dictionary is empty. */ public boolean isEmpty(); /** Gets the size of this dictionary. @return The number of entries (key-value pairs) currently in the dictionary. */ public int getSize(); /** Removes all entries from this dictionary. */ public void clear(); } // end DictionaryInterface //hasheddictionay class import java.util.Iterator; import java.util.NoSuchElementException; /** * A class that implements the ADT dictionary by using hashing and * linear probing to resolve collisions. * The dictionary is unsorted and has distinct search key. Search keys and associated values are not null. */ public class HashedDictionary implements DictionaryInterface { // The dictionary: private int numberOfEntries; private static final int DEFAULT_CAPACITY = 5; // Must be prime private static final int MAX_CAPACITY = 10000; // The hash table: private Entry[] hashTable; private int tableSize; // Must be prime private static final int MAX_SIZE = 2 * MAX_CAPACITY; private boolean integrityOK = false; private static final double MAX_LOAD_FACTOR = 0.5; // Fraction of // hash table that can be filled
  • 3. protected final Entry AVAILABLE = new Entry<>(null, null); public HashedDictionary() { this(DEFAULT_CAPACITY); // Call next constructor } // end default constructor public HashedDictionary(int initialCapacity) { initialCapacity = checkCapacity(initialCapacity); numberOfEntries = 0; // Dictionary is empty // Set up hash table: // Initial size of hash table is same as initialCapacity if it is prime; // otherwise increase it until it is prime size tableSize = getNextPrime(initialCapacity); checkSize(tableSize); // Check that size is not too large // The cast is safe because the new array contains null entries @SuppressWarnings("unchecked") Entry[] temp = (Entry[])new Entry[tableSize]; hashTable = temp; integrityOK = true; } // end constructor /* Implementations of methods in DictionaryInterface are here. . . .*/ public boolean isEmpty() { return this.numberOfEntries == 0; }//end isEmpty public Iterator getValueIterator() { throw new NoSuchElementException("Value Iterator Not Implemented");
  • 4. }//end valueIterator public void clear() { checkIntegrity(); for (int index = 0; index < this.hashTable.length; index++) { hashTable[index] = null; }//end of for this.numberOfEntries = 0; }//end clear public Iterator getKeyIterator() { return new KeyIterator(); }//end iterator public boolean contains(K key) { return getValue(key) != null; }//end contains public int getSize() { return this.numberOfEntries; }//end getSize public V remove(K key) { checkIntegrity(); int index = getHashIndex(key); while (hashTable[index] != null) { if (hashTable[index].getKey().equals(key)) { V value = hashTable[index].getValue(); hashTable[index].setValue(null); hashTable[index] = AVAILABLE;
  • 5. numberOfEntries--; return value; } index = (index + 1) % hashTable.length; } // If the key is not found, return null return null; } public V getValue(K key) { checkIntegrity(); V result = null; int index = getHashIndex(key); if ((hashTable[index] != null) && (hashTable[index] != AVAILABLE)) result = hashTable[index].getValue(); // Key found; get value // Else key not found; return null return result; } // end getValue public V add(K key, V value) { int index; V oldValue; if((key == null) || (value == null)) { throw new NoSuchElementException(); } index = getHashIndex(key); if((hashTable[index] != null) && (hashTable[index] != AVAILABLE)) { hashTable[index] = new Entry(key,value); numberOfEntries++; oldValue = null;
  • 6. } else { oldValue = hashTable[index].getValue(); hashTable[index].setValue(value); } if(isHashTableTooFull()) { enlargeHashTable(); } return oldValue; }//end of add /* END of Implementations of dictionary methods are here^. . . . */ /* Implementations of private methods are here. . . . */ //precondition: checkIntegrity has been called private void enlargeHashTable() { Entry[] oldTable = hashTable; int oldSize = hashTable.length; int newSize = getNextPrime(oldSize + oldSize); checkSize(newSize); //The cast is safe because the new array contains null entries @SuppressWarnings("unchecked") Entry[] temp = (Entry[]) new Entry[newSize]; hashTable = temp; numberOfEntries = 0;//reset number of dictionary entries, since it will be incremented by add during rehash //rehash dictionary entries from old array to the new and bigger array; //skip elements that contain null or available
  • 7. for(int index = 0; index < oldSize; index++) { if((oldTable[index] != null) && (oldTable[index] != AVAILABLE)) { add(oldTable[index].getKey(), oldTable[index].getValue()); } }// end for }//end enlargeHashTable private int getHashIndex(K key) { int hashIndex = key.hashCode() % hashTable.length; if(hashIndex < 0) { hashIndex = hashIndex + hashTable.length; } return hashIndex; }//end getHashIndex private void checkIntegrity() { if(!integrityOK) { throw new SecurityException("objecy is currupt"); } }//end checkIntegrity private boolean isHashTableTooFull() { if((numberOfEntries / hashTable.length) >= MAX_LOAD_FACTOR) {
  • 8. return true; } else { return false; } }//end isHashTableTooFull private int checkSize(int size) { if(size >= MAX_SIZE){throw new IllegalStateException("Dictionary has become too large.");} else{return size;} }//end checksize private int checkCapacity(int cap) { if(cap < DEFAULT_CAPACITY) { cap = DEFAULT_CAPACITY; } else if (cap > MAX_CAPACITY) { throw new IllegalStateException("Attempt to create a dictionary " + "whose capacity is larger than " + MAX_CAPACITY); } return cap; }//end checkcap private int getNextPrime(int integer) {
  • 9. // if even, add 1 to make od if (integer % 2 == 0) { integer++; } // end if // test odd integers while (!isPrime(integer)) { integer = integer + 2; } // end while return integer; }//end getnextprime private boolean isPrime(int integer) { boolean result; boolean done = false; // 1 and even numbers are not prime if ( (integer == 1) || (integer % 2 == 0) ) { result = false; } // 2 and 3 are prime else if ( (integer == 2) || (integer == 3) ) { result = true; } else // integer is odd and >= 5 { assert (integer % 2 != 0) && (integer >= 5); // a prime is odd and not divisible by every odd integer up to its square root result = true; // assume prime for (int divisor = 3; !done && (divisor * divisor <= integer); divisor = divisor + 2) {
  • 10. if (integer % divisor == 0) { result = false; // divisible; not prime done = true; } // end if } // end for } // end if return result; } // end isPrime /* END of Implementations of private methods are here^. . . . */ protected final class Entry { private K key; private V value; private Entry(K searchKey, V dataValue) { key = searchKey; value = dataValue; }//end contructor private K getKey() { return key; }//end getKey private V getValue() { return value; }//end value private void setValue(V newValue) { value = newValue; }//end setValue
  • 11. } // end Entry private class KeyIterator implements Iterator { private int currentIndex; // Current position in hash table private int numberLeft; // Number of entries left in iteration private KeyIterator() { currentIndex = 0; numberLeft = numberOfEntries; } // end default constructor public boolean hasNext() { return numberLeft > 0; } // end hasNext public void remove() { throw new UnsupportedOperationException(); } // end remove public K next() { K result = null; if (hasNext()) { // Skip table locations that do not contain a current entry while ( (hashTable[currentIndex] == null) || (hashTable[currentIndex] == AVAILABLE) ) { currentIndex++; } // end while result = hashTable[currentIndex].getKey(); numberLeft--; currentIndex++; }
  • 12. else throw new NoSuchElementException(); return result; } // end next } // end KeyIterator } // end HashedDictionary