【发布时间】:2013-12-03 03:26:31
【问题描述】:
对象的散列如何在 java 的 HashMap 中工作?我在想,与字符串相比,使用整数作为键是否更有效,或者这无关紧要。
如果我有:
String str = "hello";
Object helloObject = new Object();
String 的情况下什么更好?使用整数键:
HashMap<Integer, Object> hashes = new HashMap<Integer, Object>();
hashes.put(str.hashCode(), helloObject);
还是使用字符串键?
HashMap<String, Object> hashes = new HashMap<String, Object>();
hashes.put(str, helloObject);
从插入点和搜索点看什么更有效?
【问题讨论】:
-
您只需要确保 HashKey Integer 或 String 是唯一的。在
Big O Notation中搜索是 O(1)。它根据密钥直接进入它。这个 O(1) 是使用 HashMap 的要点。 -
我想知道为什么还没有一个答案提到
Big O Notation关于搜索 HashMap。 -
@user2860598 我想知道你为什么用如此错误和令人困惑的例子提到它。 “HashKey 整数或字符串是唯一的”。 “它根据密钥直接进入它”。如果可能的话,我会否决你的 cmets。
标签: java string hash hashmap key