For hashTables in Java, create a method that will calculate the maximum number of collisions and a method that will calculate the average number length of any chain in the hashtable.
Expert Answer
Hashtable.java
package venkanna;
import java.util.Scanner;
public class Hashtable
{
int a[];
int size;
int temp=0,count=0,i=0;
Hashtable(int size)
{
this.size=nextnum(size);
a=new int[this.size];
}
private static int nextnum(int size)
{
if (size%2==0)
{
size++;
}
for (; !isNext(size); size = size + 2);
return size;
}
private static boolean isNext(int size)
{
if(size==2||size==3)
{
return true;
}
if(size==1||size%2==0)
{
return false;
}
for (int i = 3; i * i <= size; i = i + 2)
if (size % i == 0)
return false;
return true;
}
public void insert(int ele)
{
a[ele%size]=ele;
if(i==0)
{
temp=ele;
i++;
}
if(temp==ele)
{
temp=ele;
count++;
}
}
public void printTable()
{
System.out.print(“nHash Table = “);
for (int i = 0; i < size; i++)
System.out.print(a[i] +” “);
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int opt,size,data;
System.out.println(“Enter The Size of HashTable”);
size=sc.nextInt();
Hashtable ht = new Hashtable(size);
do
{
System.out.println(“Enter integer element to insert”);
data=sc.nextInt();
ht.insert(data);
ht.printTable();
System.out.println(“nDo you want to Enter New Data (Type y or n) n”);
opt = sc.next().charAt(0);
} while (opt == ‘Y’ || opt == ‘y’);
ht.calculate_collision();
sc.close();
}
private void calculate_collision()
{
System.out.println(“The Maximum Number of Collisions In The HashTable is :”+count);
}
}