gpt4 book ai didi

java - 我的 Java Hashmap 实现存在问题

转载 作者:行者123 更新时间:2023-12-01 08:01:58 26 4
gpt4 key购买 nike

经过一段时间的研究和查找旧帖子后,我意识到,当您在 Java 中使用以字符串为键的 Hashmap 或 Hashtable 时,第一“轮”散列将应用于每个 String 对象的 hashCode (显然有应用于 int hashCode() 结果的第二个哈希函数,默认情况下 int hashCode() 与其调用者在内存中的位置有某种关系(来自什么)我读)。话虽这么说,如果我有一个带有开发人员定义的键类的映射,我读到我可以重写 int hashCode() 并使用我的对象的一些不同字段来返回最多每个对象可能有唯一的 int。但是,请考虑下面包含基本类型数组的代码片段。

import java.util.HashMap;

public class test
{

public static void main(String[] args) {

HashMap<char[], int[] > map = new HashMap<char[], int[]>();

String s = "Hello, World";

int x[] = { 1, 2, 3, 4, 5 };

map.put( s.toCharArray(), x );

x = map.get( s );

for ( int i : x )
System.out.print( i );
}
}

程序会因 NullPointerException 崩溃,因为 map.get( s ); 返回 null。我怀疑发生了这种情况,因为 map.put()map.get() 之间有两个不同的引用。我希望程序输出的是 1 2 3 4 5。

我的问题:如何让上面的代码片段通过键的值与键的引用来查找键?即如何让程序输出1 2 3 4 5?

编辑:我使用 HashMap 作为查找表。我正在从文件中读取字符串,需要一种快速方法来确定我刚刚读入的字符串是否在表中。

最佳答案

只需使用字符串作为 map 的键即可。

HashMap<String, int[] > map = new HashMap<String, int[]>();
String key = "array1";
int x[] = { 1, 2, 3, 4, 5 };
map.put( key, x );

字符串是不可变的,因此它是作为 map 键的不错选择。

添加另一个数组:

String key2 = "array2";
int x2[] = { 6, 7, 8, 9, 10 };
map.put( key2, x2 );

输出值:

x = map.get( key );
for ( int i : x )
System.out.print( i + " " );
}

给出

1 2 3 4 5

x = map.get( key2 );
for ( int i : x )
System.out.print( i + " " );
}

给出

6 7 8 9 10

关于java - 我的 Java Hashmap 实现存在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24823056/

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