Java.lang.ArithmeticException: / 在 LinearProbingHashSet 中为零

时间:2021-05-16 18:38:44

标签: java exception hash insert

当我运行我的代码时,我得到 ArithmeticException: / 零,我该如何纠正它。尽管我有 5 个数组大小,但为什么会出现此错误,当我运行调试时,我在 hash(Key key) 处收到错误。

我该如何更正错误消息。有人可以帮我吗?

这是我的测试课

 public static void main(String[] args) { 
HashElement<Character> he= new HashElement<Character>('p',2);
     HashElement<Character> he1= new HashElement<Character>('a',2);
     HashElement<Character> he2= new HashElement<Character>('c',1);
     HashElement<Character> he3= new HashElement<Character>('z',1);
     HashElement<Character> he4= new HashElement<Character>('d',1);
     LinearProbingHashSet<HashElement> lphs = new LinearProbingHashSet<HashElement>(10);
     
     lphs.insert(he);
     lphs.insert(he1);
     lphs.insert(he2);
     lphs.insert(he3);
     lphs.insert(he4);
     
     System.out.println(lphs);
    
    }

这是我的类 LinearProbingHashSet.java

  public class LinearProbingHashSet <Key>{
  private static int capacity ;
  private int n;          
  private int m;        
  private Key[] a;      
  private double maxLoadFactor;
  private double loadFactor;
public LinearProbingHashSet(int m){
    m = capacity;
    n= 0;  //how many element saved
    a = (Key[]) new Object[m];
    maxLoadFactor = loadFactor;
   }
public LinearProbingHashSet(){
    capacity = 4; 
 }
public int size() {
   return n;
    }
public boolean isEmpty() {
        return size() == 0;
    }
int getCapacity() {
 return m;
    
 }

 public int hash(Key key) {
 return (key.hashCode() & 0x7fffffff) % a.length;
}

void insert(Key key) {
int i;
int hashValue = hash(key); 
if(a[hashValue]==null) {   
    a[hashValue]=key;
}

 if (n >= m/2) resize(2*m);
 for (i = hashValue; a[i] != null; i = (i + 1) % m) {
     if (a[i].equals(key)) { 
            
        return; 
        }
 }
 a[i] = key;

 n++;}
 
public void resize(int capacity) {
LinearProbingHashSet<Key> temp = new LinearProbingHashSet<Key>(capacity);
 for (int i = 0; i < m; i++) {
     if (a[i] != null) {
         temp.insert(a[i]);
     }
 }
 a = temp.a;
 m= temp.m;}}

这是我的 HashElement.java

    public class HashElement<Key> implements  Comparable<HashElement<Key>> {
    private Key nyckel; //key
    private int counter; //counter
    int freq; 

  public HashElement(Key key) {
    this.nyckel = key;
    freq = 1;
    
    }

public HashElement(Key key, int counter) {
this.nyckel = key;
freq = counter;
 }

public void increment() {
freq++;
}

public void decrement() {
freq--;
 }

int getFrequencey() {
return freq;
}

public Key getKey() {
return nyckel;
}

   public void setKey(Key key) {
   key = nyckel;
   }

 public int compareTo(HashElement that) {
 int counterOne = this.getFrequencey();        
 int counterTwo = that.getFrequencey(); 


 if(counterOne < counterTwo)
     return 1;
  else if(counterOne > counterTwo)
      return -1;
  else
      return 0;  }}
      

0 个答案:

没有答案
相关问题