3

I just saw the code of contains method in java.util.Hashtable.java. It has a loop that scans through each entry in the Hashtable and compares it with the argument passed.

I read that contains method takes constant time. How is it possible when it has a loop that scans through each entry.

 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;
}
5
  • 3
    Can you post that part of the code? Commented Jan 4, 2012 at 21:52
  • Are you asking about contains or containsKey. contains checks to see if the map contains a value, which requires checking all entries. Commented Jan 4, 2012 at 21:54
  • If you are concerned about performance, you should consider HashMap or ConcurrentHashMap if you need it to be thread safe. Commented Jan 4, 2012 at 21:58
  • 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; } Commented Jan 6, 2012 at 18:49
  • What I would do is calculate the hash of that value ( which would be the bucket) and see if that value exists in that bucket. Commented Jan 6, 2012 at 19:24

1 Answer 1

7

Hashtable.contains() tries to find an entry with an equal value. It's lookups by key which are constant time (in the usual case) in hash tables.

The docs clarify this:

Tests if some key maps into the specified value in this hashtable. This operation is more expensive than the containsKey method.

Note that this method is identical in functionality to containsValue, (which is part of the Map interface in the collections framework).

Sign up to request clarification or add additional context in comments.

3 Comments

Fair enough, comment redacted :)
what is the time complexity for Hashtable.contains() method?
@user926120: Given that it has to scan through the whole table, O(n)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.