Τρίτη 24 Ιουνίου 2008

Hashtable vs. HashMap

HashMaps accept null values, while Hashtables don't.

import java.util.HashMap;
import java.util.Hashtable;

import junit.framework.TestCase;

public class HashMapTest extends TestCase {
private HashMap map = new HashMap();
private Hashtable hashtable = new Hashtable();

public void testHashMap() {
map.put("name", null);
assertNotNull(map);
assertEquals(1,map.size());
}

public void testHashtable() {
hashtable.put("name", null);
assertNotNull(hashtable);
assertEquals(1,hashtable.size());
}
}

The 2nd test simply throws a NullPointerException.

Hashtable is historical, according to JavaPractices.

1 σχόλιο:

javin paul είπε...

Hi,

This question oftenly asked in interview to check whether candidate understand correct usage of collection classes and aware of alternative solutions available.

1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.

to read more please see
Difference between HashMap and HashTable? Can we make hashmap synchronized

Thanks
Javin
Why String is immutable in Java