Our AbstractHashMap class maintains a load factor l ≤ 0.5. Reimplement that class to allow the user to specify the maximum load, and adjust the concrete subclasses accordingly.
Perform experiments on our ChainHashMap and ProbeHashMap classes to measure its efficiency using random key sets and varying limits on the load factor.
Hint The load factor can be controlled from within the abstract class, but there must be means for setting the parameter (either through the constructor, or a new method).
Write a Java application to test your solution.
Abstract Hash Map
import java.util.ArrayList;
import java.util.Random;
public abstract class AbstractHashMap<K,V> extends AbstractMap<K,V> {
protected int n = 0; // number of entries in the dictionary
protected int capacity; // length of the table
private int prime; // prime factor
private long scale, shift; // the shift and scaling factors
/** Creates a hash table with the given capacity and prime factor. */
public AbstractHashMap(int cap, int p) {
prime = p;
capacity = cap;
Random rand = new Random();
scale = rand.nextInt(prime-1) + 1;
shift = rand.nextInt(prime);
createTable();
}
/** Creates a hash table with given capacity and prime factor 109345121. */
public AbstractHashMap(int cap) { this(cap, 109345121); } // default prime
/** Creates a hash table with capacity 17 and prime factor 109345121. */
public AbstractHashMap() { this(17); } // default capacity
// public methods
@Override
public int size() { return n; }
@Override
public V get(K key) { return bucketGet(hashValue(key), key); }
@Override
public V remove(K key) { return bucketRemove(hashValue(key), key); }
@Override
public V put(K key, V value) {
V answer = bucketPut(hashValue(key), key, value);
if (n > capacity / 2) // keep load factor <= 0.5
resize(2 * capacity - 1); // (or find a nearby prime)
return answer;
}
// private utilities
/** Hash function applying MAD method to default hash code. */
private int hashValue(K key) {
return (int) ((Math.abs(key.hashCode()*scale + shift) % prime) % capacity);
}
/** Updates the size of the hash table and rehashes all entries. */
private void resize(int newCap) {
ArrayList<Entry<K,V>> buffer = new ArrayList<>(n);
for (Entry<K,V> e : entrySet())
buffer.add(e);
capacity = newCap;
createTable(); // based on updated capacity
n = 0; // will be recomputed while reinserting entries
for (Entry<K,V> e : buffer)
put(e.getKey(), e.getValue());
}
// protected abstract methods to be implemented by subclasses
/** Creates an empty table having length equal to current capacity. */
protected abstract void createTable();
protected abstract V bucketGet(int h, K k);
protected abstract V bucketPut(int h, K k, V v);
protected abstract V bucketRemove(int h, K k);
}
Probe Hash Map
import java.util.ArrayList;
public class ProbeHashMap<K,V> extends
AbstractHashMap<K,V> {
private MapEntry<K,V>[] table; // a fixed array of entries
(all initially null)
private MapEntry<K,V> DEFUNCT = new MapEntry<>(null,
null); //sentinel
// provide same constructors as base class
/** Creates a hash table with capacity 17 and prime factor
109345121. */
public ProbeHashMap() { super(); }
/** Creates a hash table with given capacity and prime factor
109345121. */
public ProbeHashMap(int cap) { super(cap); }
/** Creates a hash table with the given capacity and prime
factor. */
public ProbeHashMap(int cap, int p) { super(cap, p); }
/** Creates an empty table having length equal to current
capacity. */
@Override
@SuppressWarnings({"unchecked"})
protected void createTable() {
table = (MapEntry<K,V>[]) new MapEntry[capacity]; // safe
cast
}
/** Returns true if location is either empty or the "defunct"
sentinel. */
private boolean isAvailable(int j) {
return (table[j] == null || table[j] == DEFUNCT);
}
private int findSlot(int h, K k) {
int avail = -1; // no slot available (thus far)
int j = h; // index while scanning table
do {
if (isAvailable(j)) { // may be either empty or defunct
if (avail == -1) avail = j; // this is the first available
slot!
if (table[j] == null) break; // if empty, search fails
immediately
} else if (table[j].getKey().equals(k))
return j; // successful match
j = (j+1) % capacity; // keep looking (cyclically)
} while (j != h); // stop if we return to the start
return -(avail + 1); // search has failed
}
@Override
protected V bucketGet(int h, K k) {
int j = findSlot(h, k);
if (j < 0) return null; // no match found
return table[j].getValue();
}
@Override
protected V bucketPut(int h, K k, V v) {
int j = findSlot(h, k);
if (j >= 0) // this key has an existing entry
return table[j].setValue(v);
table[-(j+1)] = new MapEntry<>(k, v); // convert to proper
index
n++;
return null;
}
@Override
protected V bucketRemove(int h, K k) {
int j = findSlot(h, k);
if (j < 0) return null; // nothing to remove
V answer = table[j].getValue();
table[j] = DEFUNCT; // mark this slot as deactivated
n--;
return answer;
}
@Override
public Iterable<Entry<K,V>> entrySet() {
ArrayList<Entry<K,V>> buffer = new
ArrayList<>();
for (int h=0; h < capacity; h++)
if (!isAvailable(h)) buffer.add(table[h]);
return buffer;
}
}
Chain Hash Map
import java.util.ArrayList;
/*
* Map implementation using hash table with separate chaining.
*
* @author Michael T. Goodrich
* @author Roberto Tamassia
* @author Michael H. Goldwasser
*/
public class ChainHashMap<K,V> extends
AbstractHashMap<K,V> {
// a fixed capacity array of UnsortedTableMap that serve as
buckets
private UnsortedTableMap<K,V>[] table; // initialized within
createTable
// provide same constructors as base class
/** Creates a hash table with capacity 11 and prime factor
109345121. */
public ChainHashMap() { super(); }
/** Creates a hash table with given capacity and prime factor
109345121. */
public ChainHashMap(int cap) { super(cap); }
/** Creates a hash table with the given capacity and prime
factor. */
public ChainHashMap(int cap, int p) { super(cap, p); }
/** Creates an empty table having length equal to current
capacity. */
@Override
@SuppressWarnings({"unchecked"})
protected void createTable() {
table = (UnsortedTableMap<K,V>[]) new
UnsortedTableMap[capacity];
}
/**
* Returns value associated with key k in bucket with hash value
h.
* If no such entry exists, returns null.
* @param h the hash value of the relevant bucket
* @param k the key of interest
* @return associate value (or null, if no such entry)
*/
@Override
protected V bucketGet(int h, K k) {
UnsortedTableMap<K,V> bucket = table[h];
if (bucket == null) return null;
return bucket.get(k);
}
/**
* Associates key k with value v in bucket with hash value h,
returning
* the previously associated value, if any.
* @param h the hash value of the relevant bucket
* @param k the key of interest
* @param v the value to be associated
* @return previous value associated with k (or null, if no such
entry)
*/
@Override
protected V bucketPut(int h, K k, V v) {
UnsortedTableMap<K,V> bucket = table[h];
if (bucket == null)
bucket = table[h] = new UnsortedTableMap<>();
int oldSize = bucket.size();
V answer = bucket.put(k,v);
n += (bucket.size() - oldSize); // size may have increased
return answer;
}
/**
* Removes entry having key k from bucket with hash value h,
returning
* the previously associated value, if found.
* @param h the hash value of the relevant bucket
* @param k the key of interest
* @return previous value associated with k (or null, if no such
entry)
*/
@Override
protected V bucketRemove(int h, K k) {
UnsortedTableMap<K,V> bucket = table[h];
if (bucket == null) return null;
int oldSize = bucket.size();
V answer = bucket.remove(k);
n -= (oldSize - bucket.size()); // size may have decreased
return answer;
}
/**
* Returns an iterable collection of all key-value entries of the
map.
*
* @return iterable collection of the map's entries
*/
@Override
public Iterable<Entry<K,V>> entrySet() {
ArrayList<Entry<K,V>> buffer = new
ArrayList<>();
for (int h=0; h < capacity; h++)
if (table[h] != null)
for (Entry<K,V> entry : table[h].entrySet())
buffer.add(entry);
return buffer;
}
}
Our AbstractHashMap class maintains a load factor l ≤ 0.5. Reimplement that class to allow the...
1-Suppose you write an application in which one class contains code that keeps track of the state of a board game, a separate class sets up a GUI to display the board, and a CSS is used to control the stylistic details of the GUI (for example, the color of the board.) This is an example of a.Duck Typing b.Separation of Concerns c.Functional Programming d.Polymorphism e.Enumerated Values 2-JUnit assertions should be designed so that they a.Fail (ie, are false) if...
Y. Daniel Liang’s 8 Class Design Guidelines were posted on the File Manager and handed out in class. Please choose 5 guidelines and discuss them in depth. For each guideline, use 1 page or more for your discussion. You can use the code provided in class to demonstrate your points. The code should not be more than one-third of your writing. 1. Cohesion • [✓] A class should describe a single entity, and all the class operations should logically fit...
Java Painter Class This is the class that will contain main. Main will create a new Painter object - and this is the only thing it will do. Most of the work is done in Painter’s constructor. The Painter class should extend JFrame in its constructor. Recall that you will want to set its size and the default close operation. You will also want to create an overall holder JPanel to add the various components to. It is this JPanel that...
CS 1102 Unit 5 – Programming Assignment In this assignment, you will again modify your Quiz program from the previous assignment. You will create an abstract class called "Question", modify "MultipleChoiceQuestion" to inherit from it, and add a new subclass of "Question" called "TrueFalseQuestion". This assignment will again involve cutting and pasting from existing classes. Because you are learning new features each week, you are retroactively applying those new features. In a typical programming project, you would start with the...
CS 1102 Unit 5 – Programming Assignment In this assignment, you will again modify your Quiz program from the previous assignment. You will create an abstract class called "Question", modify "MultipleChoiceQuestion" to inherit from it, and add a new subclass of "Question" called "TrueFalseQuestion". This assignment will again involve cutting and pasting from existing classes. Because you are learning new features each week, you are retroactively applying those new features. In a typical programming project, you would start with the...
Please explain each line of code, all code will be in Java. Thank you JKL Restaurant maintains a members’ club for its customers. There are three levels of membership: (1) Basic, (2) Silver, and (3) Gold. A certain member has to be exactly a Basic, Silver, or Gold member at any point in time. Whenever a member spends money at JKL, he/she gets points and as these points are accumulated, one can redeem one or more $20 dining certificates. Each Gold member can...
Modify the LinkedCollection class to be a SortedLinkedCollecton class and see how that effects our implementation for adding and removing items. You should reference the SortedArrayCollection class provided for how these algorithms should be implemented. What needs to change here? Is it a lot of code or not much? Include a toString method that creates and returns a string that correctly represents the current collection. Include a test driver application that demonstrates your class correctly. //--------------------------------------------------------------------------- // LinkedCollection.java // //...
In a new file located in the same package as the class Main, create a public Java class to represent a photograph that consists of a linear (not 2D) array of pixels. Each pixel is stored as an integer. The photograph class must have: (a) Two private fields to represent the information stored about the photograph. These are the array of integers and the date the photograph was taken (stored as a String). The values in the array must be...
C# - Inheritance exercise
I could not firgure out why my code was not working. I was
hoping someone could do it so i can see where i went wrong.
STEP 1: Start a new C# Console Application project and rename its main class Program to ZooPark. Along with the ZooPark class, you need to create an Animal class. The ZooPark class is where you will create the animal objects and print out the details to the console. Add the...
Additional code needed:
PartA: BurgerOrder class (1 point) Objective: Create a new class that represents an order at a fast-food burger joint. This class will be used in Part B, when we work with a list of orders. As vou work through this part and Part B, draw a UML diagram of each class in using the UML drawing tool 1) Create a new Lab5TestProject project in Netbeans, right-click on the lab5testproject package and select New>Java Class 2) Call your...