对于我的任务,我们需要创建一个字符串哈希表,我已经使用整数创建了一个,它运行得很好,但我现在遇到了麻烦。
我一直在为我输入的字符串获取java.lang.NumberFormatExceptions
,我不确定为什么会发生这种情况。以下是我用于HashTable类的代码;
public class HashTable {
private SortedList[] hashArray;
private int arraySize;
public HashTable(int size) {
arraySize = size;
hashArray = new SortedList[arraySize];
for(int i = 0; i < arraySize; i++) {
hashArray[i] = new SortedList();
}
} // END HashTable()
public void displayTable() {
for(int i = 0; i < arraySize; i++) {
System.out.print(i + ". ");
hashArray[i].displayList();
}
} // END displayTable()
public int hash(String key) {
int hashkey = Integer.parseInt(key);
return hashkey % arraySize;
} // END hash()
public void insert(Link link) {
String key = link.getKey();
int hashVal = hash(key);
hashArray[hashVal].insert(link);
} // END insert()
public void delete(String key) {
int hashVal = hash(key);
hashArray[hashVal].delete(key);
} // END delete()
} // END HashTable
这是列表的代码:
public class SortedList {
private Link first;
public void SortedList() {
first = null;
} //END SortedList()
public void insert(Link link) {
String key = link.getKey();
Link previous = null;
Link current = first;
while(current != null && key.compareTo(current.getKey()) > 0) {
previous = current;
current = current.getNext();
}
if(previous == null) {
first = link;
} else {
previous.setNext(link);
link.setNext(current);
}
} // END insert()
public void delete(String key) {
Link previous = null;
Link current = first;
while(current != null && !key.equals(current.getKey())) {
previous = current;
current = current.getNext();
}
if(previous == null) {
first = first.getNext();
} else {
previous.setNext(current.getNext());
}
} // END delete()
public Link find(String key) {
Link current = first;
while(current != null && current.getKey().compareTo(key) <= 0) {
if(current.getKey().equals(key)) {
return current;
}
current = current.getNext();
}
return null;
} // END find()
public void displayList() {
System.out.print("List (first -> last): ");
Link current = first;
while(current != null) {
current.displayLink();
current = current.getNext();
}
System.out.println();
} // END displayList()
} //END SortedList()
Link类只是一个基本的类,我收到了错误:
int hashkey = Integer.parseInt(key);
在散列函数中,在我的HashTable类中。
编辑:据我所知,我需要将字符串转换为整数,然后执行哈希函数来获取其位置的索引。
因为Hashtable.insert
和Hashtable.delete
中的link.getKey()
和key
变量允许传递所有Strings
。你可能应该使用
public int hash(String key) {
int hashkey = key.hashCode();
return hashkey % arraySize;
} // END hash()
要将String
key
转换为整数以使用哈希键,请使用key.hashCode()
。
看起来您正在尝试将字符串转换为Integer,其中字符串实际上并不代表数字
int hashkey = Integer.parseInt(key);
如果你想获得字符串键的散列码,你可以简单地调用
int hashkey = key.hashCode();
您传递的字符串不是有效的整数字符串。根据Integer#parseInt()
JavaDoc:
投掷:
NumberFormatException
-如果字符串不包含可解析的整数。
找到一种不同的方法将字符串转换为整数。提示:String#hashCode()
。