| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- public class Hashtable<T> {
- public static void main(String[] args) {
- Hashtable<String> ht = new Hashtable<String>();
- String s1 =
- "The divine rights of kings was a political " +
- "philosophy espoused by Chucky One back in the " +
- "day who lost his head on account of him being " +
- "a dumbass";
- String[] words = s1.split(" ");
- for (String s : words) ht.add(s);
- ht.printArray();
- int longestChain = ht.longestChain();
- int numberOfChains = ht.numberOfChains();
- // LINEAR PROBING :
- // Longest Chain : 4
- // Number of Chains : 3
- //
- // QUADRADIC PROBING :
- // Longest Chain : 4
- // Number of Chains : 2
- //
- // Less chains = quicker fetching
- System.out.println(
- "Longest Chain : " +
- longestChain +
- "\nNumber of Chains : " +
- numberOfChains
- );
- }
- private T[] table;
- private int size;
- private float loadFactor;
- public Hashtable() {
- this(11);
- }
- public Hashtable(int initialCapacity) {
- table = (T[]) new Object[initialCapacity];
- size = 0;
- loadFactor = 0.75f;
- }
- public void add(T elem) {
- if (size / (double) table.length > loadFactor) rehash();
- int i = Math.abs(elem.hashCode()) % table.length;
- int t = 0;
- while (table[i] != null) {
- // Linear Probing
- // i = (i + 1) % table.length;
- // Quadratic Probing
- i = (i + (t ^ 2)) % table.length;
- t++;
- }
- table[i] = elem;
- size++;
- }
- public boolean contains(T elem) {
- int i = Math.abs(elem.hashCode()) % table.length;
- int t = 0;
- while (table[i] != null && !table[i].equals(elem)) {
- // Linear Probing
- // i = (i + 1) % table.length;
- // Quadratic
- i = (i + (t ^ 2)) % table.length;
- }
- return table[i] != null;
- }
- public void printArray() {
- for (int i = 0; i < table.length; i++) System.out.println(
- i + ": " + table[i]
- );
- }
- public int longestChain() {
- int longest = 0;
- for (int i = 0; i < table.length; i++) {
- int j = i;
- while (i < table.length && table[i] != null) {
- i++;
- }
- int lengthOfChain = i - j;
- if (lengthOfChain > longest) longest = lengthOfChain;
- }
- return longest;
- }
- public int numberOfChains() {
- int threeOrMoreChains = 0;
- for (int i = 0; i < table.length; i++) {
- int j = i;
- while (i < table.length && table[i] != null) {
- i++;
- }
- int lengthOfChain = i - j;
- if (lengthOfChain > 3) threeOrMoreChains++;
- }
- return threeOrMoreChains;
- }
- public int size() {
- return size;
- }
- private void rehash() {
- T[] smallTable = table;
- table = (T[]) new Object[table.length * 2 + 1];
- for (int i = 0; i < smallTable.length; i++) if (
- smallTable[i] != null
- ) add(smallTable[i]);
- }
- }
|