WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Core Java Β· Intermediate Β· question 32 of 100

What is a hash table in Java? How is it different from a HashMap?

πŸ“• Buy this interview preparation book: 100 Core Java questions & answers β€” PDF + EPUB for $5

A hash table in Java is a data structure that maps keys to values using a hash function. A hash function takes a key as input and returns an index into an array, where the value associated with the key is stored. Hash tables are often used for fast lookups, inserts, and deletes of key-value pairs.

In Java, the Hashtable class is a concrete implementation of a hash table. It is a legacy class that has been around since the early days of Java, and it is synchronized, meaning that it is thread-safe but slower than other implementations.

A HashMap is a more modern implementation of a hash table in Java. It is similar to a Hashtable, but it is not synchronized, making it faster but not thread-safe. It is also more efficient in terms of memory usage, as it does not require the overhead of synchronization.

Here’s an example of how to use a HashMap in Java:

// create a new HashMap
HashMap<String, Integer> myMap = new HashMap<String, Integer>();

// add some key-value pairs to the map
myMap.put("apple", 1);
myMap.put("banana", 2);
myMap.put("cherry", 3);

// get the value associated with a key
int value = myMap.get("banana");

// remove a key-value pair from the map
myMap.remove("cherry");

In this example, we create a new HashMap and add some key-value pairs to it. We then use the get() method to retrieve the value associated with the key "banana", and the remove() method to remove the key-value pair associated with the key "cherry".

In summary, a hash table in Java is a data structure that maps keys to values using a hash function. The Hashtable class is a legacy implementation of a hash table that is synchronized, while the HashMap class is a more modern implementation that is not synchronized and more memory-efficient. HashMap is generally preferred over Hashtable in modern Java programming.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview β€” then scores it.
πŸ“ž Practice Core Java β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Core Java questions & answers β€” PDF + EPUB for $5

All 100 Core Java questions Β· All topics