具有链表实现和存储文本文件的哈希表 [英] Hash table with linked list implementation and storing text file
问题描述
我想使用链表和链表实现自己的哈希表,但是我很难确定如何在main方法中使用实现.我需要读取一个用数据分隔的逗号分隔值文件,并将名称存储为键,并将两个浮点存储为值.我知道我需要使用面向对象的编程,但是我很难通过自己的实现来访问数据.
I want to implement my own hash table using chaining and linked list but I am having a hard time figuring out how to use the implementation in the main method. I need to read a comma separated values file with data and store the names as keys and the two floating points as a value. I know I need to use object oriented programming but I having a difficult time accessing my data using my implementation.
这是我的代码: 公共类LinkedListHash {
Here is my code: public class LinkedListHash{
String key;
String value;
LinkedListHash next;
public LinkedListHash(){
}
LinkedListHash(String key, String value){
this.key = key;
this.value = value;
this.next = null;
}
public String getValue(){
return value;
}
public void setValue(String value){
this.value = value;
}
public String getKey(){
return key;
}
public LinkedListHash getNext(){
return next;
}
public void setNext(LinkedListHash next){
this.next = next;
}
class Hashtable {
int size = 0;
LinkedListHash[] table;
Hashtable(){
table = new LinkedListHash[size];
for (int i = 0; i < size; i++){
table[i] = null;
}
}
public String get(String key){
int hash = key.hashCode();
if (table[hash] == null){
return null;
}
else {
LinkedListHash input = table[hash];
while (input != null && input.getKey() != key){
input = input.getNext();
}
if (input == null){
return null;
}
else {
return input.getValue();
}
}
}
public void put(String key, String value){
int hash = key.hashCode();
if (table[hash] == null){
table[hash] = new LinkedListHash(key, value);
}
else {
LinkedListHash input = table[hash];
while (input.getNext() != null && input.getKey() != key){
input = input.getNext();
}
if (input.getKey() == key){
input.setValue(value);
}
else {
input.setNext(new LinkedListHash(key, value));
}
}
}
}
}
public static void main(String[] args) throws FileNotFoundException{
Hashtable<String, String> tbl = new Hashtable<String, String>();
String path = args[0];
if(args.length < 1) {
System.out.println("Error, usage: java ClassName inputfile");
System.exit(1);
}
Scanner reader = new Scanner(new FileInputStream(args[0]));
while((path = reader.nextLine()) != null){
String parts[] = path.split("\t");
tbl.put(parts[0], parts[1]);
} reader.close();
} }
任何可以改善我的代码的方式都会有所帮助. 请记住,我不是一个非常有经验的程序员,所以对于任何可怕的错误我深表歉意.
Any way I could improve my code would be helpful. Keep in mind I am not a very experienced programmer so I apologize for any horrendous mistakes.
推荐答案
String
s不应与==
或!=
进行比较,除非您想知道它们是否是相同的字符串且占用相同的内存位置.改为使用equals()
.
String
s should not be compared with ==
or !=
unless you want to know if they are the same string occupying the same memory location. Use equals()
instead.
这篇关于具有链表实现和存储文本文件的哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!