gpt4 book ai didi

java - hashCode 冲突将两个不同的词放在同一位置

转载 作者:行者123 更新时间:2023-11-29 05:29:00 28 4
gpt4 key购买 nike

我应该用哈希表实现一个接口(interface)。问题是我得到了错误的输出,这是由于碰撞(据我了解)。我并没有完全独立地编写这段代码,我一直在寻求帮助。我不是 Java 的大师,我的类(class)还很早,所以这对我来说很难,所以请耐心等待。

到目前为止,这是我的代码:

runStringDictionary.java

import java.io.BufferedReader;
import java.io.FileReader;

public class runStringDictionary {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

if (args.length == 0 || args.length > 1) {
System.out.println("Syntax to run the program: java runStringDictionary <inputFile>");
}
if (args.length == 1) {
try {

Dictionary myDictionary = new Dictionary(); //Initialize a Dictionary to store input words
BufferedReader br = new BufferedReader(new FileReader(args[0])); //Read the text file input
String line;

while ((line = br.readLine()) != null) {//Read each line
String[] strArray = line.split(" "); //Separate each word in the line and store in another Array
for (int i = 0; i < strArray.length; i++) { //Loop over the Array
if (myDictionary.contains(strArray[i])) { //Check if word exists in the dictionary
myDictionary.remove(strArray[i]); //if it does remove it
} else {
myDictionary.add(strArray[i]); //if it doesn't then add it
}
}
}//while loop ends

//print the contents of myDictionary
for (int i = 0; i < 25; i++) {
if (myDictionary.table[i] != null) {
System.out.println(myDictionary.table[i]);
}
}

} catch (Exception e) {
System.out.println("Error found : " + e);
}
}
}
}

StringDictionary.java

public interface StringDictionary {

public boolean add(String s);

public boolean remove(String s);

public boolean contains(String s);
}

Dictionary.java

public class Dictionary implements StringDictionary {
private int tableSize = 25;
Object[] table;

// constructor
Dictionary() {
this.table = new Object[this.tableSize];
}

@Override
public boolean add(String s) {
// TODO Auto-generated method stub
int hashCode = s.hashCode() % this.tableSize;
if (!this.contains(s)) {
this.table[hashCode] = s;
}
return false;
}

@Override
public boolean remove(String s) {
// TODO Auto-generated method stub
int hashCode = s.hashCode() % this.tableSize;
if (this.contains(s)) {
this.table[hashCode] = null;
return true;
}
return false;
}

@Override
public boolean contains(String s) {
// TODO Auto-generated method stub
int hashCode = s.hashCode() % this.tableSize;
if (table[hashCode] != null) {
if (table[hashCode].equals(s))
return true;
}
return false;
}
}

最佳答案

Hashcode 冲突是意料之中的,也是正常的;哈希码用于缩小潜在匹配范围,然后必须检查这些潜在匹配的规范相等性。

关于java - hashCode 冲突将两个不同的词放在同一位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21766611/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com