【发布时间】:2012-02-02 19:23:33
【问题描述】:
我刚刚在java.util.Hashtable.java中看到了contains方法的代码。它有一个循环扫描 Hashtable 中的每个条目并将其与传递的参数进行比较。
我读到包含方法需要恒定的时间。当它有一个扫描每个条目的循环时,这怎么可能呢。
public synchronized boolean contains(Object value) {
if (value == null) {
throw new NullPointerException();
}
Entry tab[] = table;
for (int i = tab.length ; i-- > 0 ;) {
for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) {
if (e.value.equals(value)) {
return true;
}
}
}
return false;
}
【问题讨论】:
-
你能把那部分代码贴出来吗?
-
你问的是 contains 还是 containsKey。 contains 检查地图是否包含值,这需要检查所有条目。
-
如果你关心性能,如果你需要它是线程安全的,你应该考虑HashMap或ConcurrentHashMap。
-
public synchronized boolean contains(Object value) { if (value == null) { throw new NullPointerException(); } 条目选项卡 [] = 表; for (int i = tab.length ; i-- > 0 ;) { for (Entry
e = tab[i] ; e != null ; e = e.next) { if (e.value.等于(值)){返回真; } } } 返回错误; } -
我要做的是计算该值的哈希值(这将是存储桶)并查看该值是否存在于该存储桶中。