Sam*_*uel 7 java string hash key hashmap
对象的散列如何在java的HashMap中工作?我想,与字符串相比,使用整数作为键是否更有效,或者它是否无关紧要.
如果我有:
String str = "hello";
Object helloObject = new Object();
Run Code Online (Sandbox Code Playgroud)
在String的情况下更好的是什么?使用整数键:
HashMap<Integer, Object> hashes = new HashMap<Integer, Object>();
hashes.put(str.hashCode(), helloObject);
Run Code Online (Sandbox Code Playgroud)
或使用String键?
HashMap<String, Object> hashes = new HashMap<String, Object>();
hashes.put(str, helloObject);
Run Code Online (Sandbox Code Playgroud)
从插入点到搜索点有什么效率?
请记住,具有相同哈希码的两个字符串可能不相等.
如果使用字符串的hashCode而不是字符串本身,则两个不同的字符串可以生成相同的映射键,这可能会导致奇怪的行为.
试试这个代码,看看我的意思.
Map<Integer, String> map = new HashMap<Integer, String>();
map.put("FB".hashCode(), "FB");
map.put("Ea".hashCode(), "Ea");
System.out.println(map.get("FB".hashCode()));
Run Code Online (Sandbox Code Playgroud)
将输出
Ea
Run Code Online (Sandbox Code Playgroud)
因为
"FB".hashCode() == "Ea".hashCode() // is true
Run Code Online (Sandbox Code Playgroud)
因此,您应该更好地使用String键作为键.
要做到正确的第一件事应该是正确性,而不是效率:这段代码
HashMap<Integer, Object> hashes = new HashMap<Integer, Object>();
hashes.put(str.hashCode(), helloObject);
Run Code Online (Sandbox Code Playgroud)
是不正确的(除了效率低*).
回想一下,哈希码不是唯一的.根据Java文档的唯一要求是相同对象的哈希码是相同的.但是,具有相同哈希码的对象不一定相等.结果,改变你的哈希映射的密钥String来Integer改变语义:两个完全不同的对象可以根据它们的哈希码绝对任意地被认为是相同的密钥.
hashCode()返回一个原语int,java.lang.Integer由编译器包装在一个原语中.这通常会导致在使用a时没有创建其他对象的情况下创建不需要的对象String.
| 归档时间: |
|
| 查看次数: |
6323 次 |
| 最近记录: |