Java 为什么会发生此ArrayIndexOutOfBounds异常?
我正在尝试用哈希表实现一个字典(不是使用Java提供的哈希表类,而是从头制作)。下面是my Dictionary类中的Java 为什么会发生此ArrayIndexOutOfBounds异常?,java,arrays,hash,indexoutofboundsexception,Java,Arrays,Hash,Indexoutofboundsexception,我正在尝试用哈希表实现一个字典(不是使用Java提供的哈希表类,而是从头制作)。下面是my Dictionary类中的insert()方法,用于将元素插入包含在特定数组位置的链表中 我正在运行一个提供的测试程序来确定Dictionary类是否工作,但在到达某个点时,我遇到了一个ArrayIndexOutOfBoundsException:-5980。以下是具体的测试。为什么会出现这种例外情况?(如果需要,我可以提供更多代码!) 插入: public int insert(DictEntry pa
insert()
方法,用于将元素插入包含在特定数组位置的链表中
我正在运行一个提供的测试程序来确定Dictionary类是否工作,但在到达某个点时,我遇到了一个ArrayIndexOutOfBoundsException:-5980
。以下是具体的测试。为什么会出现这种例外情况?(如果需要,我可以提供更多代码!)
插入:
public int insert(DictEntry pair) throws DictionaryException {
String entryConfig = pair.getConfig();
int found = find(entryConfig);
if (found != -1) {
throw new DictionaryException("Pair already in dictionary.");
}
int entryPosition = hash(entryConfig);
if (dict[entryPosition] == null) { //Dictionary.java:54
LinkedList<DictEntry> list = new LinkedList<DictEntry>();
dict[entryPosition] = list;
list.add(pair);
return 0;
} else {
LinkedList<DictEntry> list = dict[entryPosition];
list.addLast(pair);
return 1;
}
}
散列函数:
private int hash(String config) {
int expBase = 41;
int exp;
int ASCIIChar;
int hashedConfig = 0;
for (int i = 0; i < config.length(); i++) {
ASCIIChar = (int)config.charAt(i);
exp = (int)Math.pow(expBase, i);
hashedConfig = hashedConfig + (ASCIIChar * exp);
}
hashedConfig = hashedConfig % dictSize;
return hashedConfig;
}
private int hash(字符串配置){
int-expBase=41;
国际贸易;
内阿希卡;
int hashedConfig=0;
对于(int i=0;i
正确-正如所怀疑的那样,问题在于哈希()
。这:
hashedConfig = hashedConfig % dictSize;
。。。并不能保证它是积极的。如果一开始是负数,你仍然会得到一个负数。您可以使用:
hashedConfig = Math.abs(hashedConfig % dictSize);
或:
hashedConfig=hashedConfig%dictSize;
if(hashedConfig<0){
hashedConfig+=dictSize;
}
这两种方法都可以得到正确范围内的值,但您可能会发现后者更为统一
请注意,哈希代码也非常低效。一开始就不清楚为什么不使用String.hashCode()
。(您仍然需要将任意32位整数转换为数组元素范围内的值,但至少哈希本身会更快。)
exp = (int)Math.pow(expBase, i);
hashedConfig = hashedConfig + (ASCIIChar * exp);
将溢出整数范围,因此生成负数。在返回hashedConfig之前添加一个Math.abs
您可能应该分析这会如何影响哈希函数的分布。请同时发布您的
哈希
函数请声明您的entryPosition>=0&&entryPosition
听起来问题很简单,就是哈希()
没有做它应该做的事情-尤其是,它给了你一个负数。如果它要给出一个范围[0…dict.length)
内的值,那么它显然被破坏了。很抱歉,我在底部添加了哈希函数。我讨厌java没有无符号整数。
hashedConfig = Math.abs(hashedConfig % dictSize);
hashedConfig = hashedConfig % dictSize;
if (hashedConfig < 0) {
hashedConfig += dictSize;
}
exp = (int)Math.pow(expBase, i);
hashedConfig = hashedConfig + (ASCIIChar * exp);